我在测试我的一个组件时遇到了一些麻烦。测试如下:
describe('SmpEventsNewCompactEventComponent', () => {
const specService: SmpSpecService = new SmpSpecService();
describe('Component rendering', () => {
let componentInstance: any;
let componentFixture: ComponentFixture<any>;
let cssSelector: string;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
MaterialModule.forRoot()
],
declarations: [
SmpEventsCompactEventComponent,
SmpEventsAddressComponent
],
providers: [
{ provide: SMP_OT_HELPER, useValue: newOtHelperInstance() },
DatePipe,
SmpEventTypeCheckerService,
SmpLangService
]
});
componentFixture = TestBed.createComponent(SmpEventsCompactEventComponent);
componentInstance = componentFixture.componentInstance;
});
describe('Global', () => {
it('GIVEN there are date/time AND address ' +
'WHEN component loads THEN display event', () => {
//// TEST ONE
componentInstance.isEventEnabled = true;
cssSelector = '.events-compact-event';
let debugElement = specService.queryDebugElement(
componentFixture, cssSelector);
expect(debugElement).not.toBeNull();
});
it('GIVEN there are no date/time AND no address ' +
'WHEN component loads THEN do not display event', () => {
//// TEST TWO
componentInstance.isEventEnabled = true;
//componentInstance.isAddressEnabled = false;
// componentInstance.isDateEnabled = false;
cssSelector = '.events-compact-event';
let debugElement = specService.queryDebugElement(
componentFixture, cssSelector);
console.log('--------------', debugElement.nativeElement);
// expect(debugElement.nativeElement).toBe(null);
// expect(true).toBe(true);
expect(debugElement).not.toBeNull();
});
});
});
specService.queryDebugElement 如下:
queryDebugElement(fixture: ComponentFixture<any>, cssSelector: string): DebugElement {
fixture.detectChanges();
return fixture.debugElement.query(By.css(cssSelector));
}
每当我使用
expect(true).toBe(true);
或者
expect(debugElement.nativeElement).toBe(null);
或者
expect(debugElement).not.toBeNull();
在测试二中,测试正常工作或失败,但每当我使用
expect(debugElement).toBeNull();
karma crash 使用的浏览器(使用 chrome/chromium/PhantomJs 测试)并且没有给出任何关于发生了什么的线索。这不是一个简单的“期望假为真”失败,测试上下文完全崩溃。
你看到什么可以解释这种行为了吗?
最佳答案
使用 expect(debugElement).toBeTruthy();
而不是 expect(debugElement).not.toBeNull()
因为当某些事情未定义时 not.tobeNull()
可能不会按预期运行。如果您的 debugElement
未定义,则可能会产生问题。