我是刚开始使用Angular编写单元测试。我试图编写一个测试来验证单击按钮时下拉菜单是否打开。这是相关的HTML:
<button mat-button class="requestMenu" [matMenuTriggerFor]="requestMenu">Requests</button>
<mat-menu #requestMenu="matMenu" yPosition="below">
<button mat-menu-item>{{'dashboard.header.screen_options.action_required.option_text' | i18next}}</button>
<button mat-menu-item>My Requests</button>
<button mat-menu-item>Assigned to Me</button>
<button mat-menu-item>Unassigned</button>
<button mat-menu-item>View All</button>
</mat-menu>
这是我所能进行的测试:
it('should show request menu if "Requests" is clicked', () => {
expect(fixture.debugElement.query(By.css('.requestMenu')).nativeElement).toBe(false);
const button = fixture.debugElement.query(By.css('.requestMenu')).nativeElement;
button.click();
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.requestMenu')).nativeElement).toBe(true);
});
我收到错误消息:Expected HTMLNode to be false.
有人可以帮忙吗?
这是描述代码。可能有些矫kill过正,但我希望它能提供一个线索:
describe('HeaderComponent', () => {
let component: HeaderComponent;
let fixture: ComponentFixture<HeaderComponent>;
let logger: LogService;
class MockLogService {
getData(): Observable<any[]> { return Observable.of([]); }
debug() {
this.writeDebug();
}
error() {
this.writeError();
}
info() {
this.writeInfo();
}
writeInfo() {
return;
}
writeDebug() {
return;
}
writeError() {
return;
}
}
class MockAppSandboxService {
setMainProgressBar() {}
}
beforeAll(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule,
platformBrowserDynamicTesting());
});
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
SearchBarModule,
TestingModule,
FormsModule,
MaterialModule,
FlexLayoutModule,
ReactiveFormsModule,
SafePipeModule,
EffectsModule,
NgProgressModule.withConfig(env.progressBarConfig),
I18NextModule.forRoot(),
StoreModule.forRoot({})
],
declarations: [
NotificationsComponent,
BadgeComponent,
UsernameIconComponent,
PreferencesComponent,
HeaderComponent
],
providers: [
CustomIconService,
SidenavService,
{ provide: LogService, useClass: MockLogService },
{ provide: AppSandboxService, useClass: MockAppSandboxService },
[Store],
Actions
],
schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
logger = TestBed.get(LogService);
fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
afterEach(() => {
fixture.destroy();
});
答案 0 :(得分:0)
您的问题是您断言一个对象等效于false
。您也没有获取要测试其可见性的元素。我认为您的意图是编写一个执行以下操作的测试:
it('should show request menu if "Requests" is clicked', () => {
expect(fixture.debugElement.query(By.css('#requestMenu'))).toBeFalsy();
const button = fixture.debugElement.query(By.css('.requestMenu')).nativeElement;
button.click();
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('#requestMenu'))).toBeTruthy();
});
更改模板以在要切换的元素上具有ID:
<mat-menu id="requestMenu" #requestMenu="matMenu" yPosition="below">