dec*_*bal 1 unit-testing karma-jasmine angular
我想测试按钮的功能,但该元素在页面上不可见,因为它位于*ngIf. 我想将变量 from 设置*ngIf为 true,以便能够显示数据。我尝试这样做:
beforeEach(() => {
fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
component.currentUser = {firstName: 'xxx'} as User; // Changing currentUser so it won't be undefined anymore
fixture.detectChanges();
});
Run Code Online (Sandbox Code Playgroud)
但仍然不起作用。这是我的组件:
<div class="menu-button-container">
<div class="menu-button" [ngClass]="{'menu-open': isMenuOpen}" (click)="toggleMenu()" *ngIf="currentUser">
<div class="line-menu-button line-menu-button__top"></div>
<div class="line-menu-button line-menu-button__middle"></div>
<div class="line-menu-button line-menu-button__bottom"></div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
以及我尝试运行的测试:
it('should open the menu when the button menu is clicked', () => {
const fixture = TestBed.createComponent(HeaderComponent);
fixture.detectChanges();
const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
expect(menuDebugElement).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)
这总是失败。如果我将*ngIf规则定义为*ngIf="currentUser",则测试有效。我怎样才能从测试中改变这个变量?请指教!谢谢!
更改 currentUser 变量的值:
it('should open the menu when the button menu is clicked', () => {
const fixture = TestBed.createComponent(HeaderComponent);
const component = fixture.componentInstance;
component.currentUser = true;
fixture.detectChanges();
const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
expect(menuDebugElement).toBeTruthy();
});
Run Code Online (Sandbox Code Playgroud)
我创建了一个完整的测试,它对我有用
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TestTComponent } from './test-t.component';
import { By } from '@angular/platform-browser';
fdescribe('TestTComponent', () => {
let component: TestTComponent;
let fixture: ComponentFixture<TestTComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestTComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestTComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
component.currentUser = true;
fixture.detectChanges();
const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
expect(menuDebugElement).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13267 次 |
| 最近记录: |