【发布时间】:2021-01-23 05:51:15
【问题描述】:
这是我的 oninit 类,我不应该更改它。
ngOnInit(): void {
this.setCustomizedValues();
this.sub = PubSub.subscribe('highlightEntity', (subId, entityIdentifier: string) => {
document.querySelector(entityIdentifier).classList.add('highlight');
setTimeout(() => {
document.querySelector(entityIdentifier).classList.remove('highlight');
}, 2000);
});
}
这是最小的测试设置
describe('aComponent', () => {
let httpCallerServiceStub = jasmine.createSpyObj('httpCallerServiceStub', ['get']);
let fixture: ComponentFixture<aComponent>;
let componentInstance: aComponent;
localStorage.clear();
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [aComponent],
providers: [
{
provide: HttpCallerService,
useValue: httpCallerServiceStub
}],
imports: [CommonModule, CmcSpinnerModule, NgbModule],
}).compileComponents();
fixture = TestBed.createComponent(aComponent);
componentInstance = fixture.componentRef.instance;
fixture.autoDetectChanges();
});
describe('ngOnInit method', () => {
beforeEach(() => {
fixture.componentInstance.customized = {};
});
it('should initialize with minimum input', () => {
// Triggers ngOnInit
fixture.detectChanges();
expect(fixture.componentInstance.customized).toEqual({});
});
});
问题是测试随机失败,错误是 classlist not found of null
"message": "An error was thrown in afterAll\nTypeError: Cannot read property 'classList' of null\n at <Jasmine>\n
at webpack:///components/path/aComponent.ts:35:53
第 35 行引用 oninit 函数中的这一行
setTimeout(() => {
document.querySelector(entityIdentifier).classList.remove('highlight');
}, 2000);
这里的问题很少
-
我尝试将 tick(2000) 和 fake asysnc 放在一个简单的 ngoni 测试中,但它仍然给我同样的随机错误(如 this answer 所建议的那样)
-
我的测试台配置是否缺少某些内容?因为即使我注释掉 oninit 测试并检查一些随机函数,即使没有fixture.detectChanges(),也会发生同样的随机错误。
-
如果我使用 fdescibe 运行测试,所有测试每次都会通过。仅当我从 fdescribe 中删除 f 并同时运行其他组件的所有测试时才会出现此问题。
请指导我,自从过去 4 天以来,我一直被困在这里。
【问题讨论】:
-
从
fdescribe工作的事实来看,我感觉测试失败是因为某些使用aComponent的组件。如果是这种情况,请尝试模拟aComponent另一个单元测试。 -
好的,我会这样做,所以当 aComponent 规范中没有测试时,另一个使用 aComponent 的组件不会失败
-
aComponent在ngOnInit中有一些逻辑,并且它没有在父组件的单元测试中正确实例化。尝试为它提供一个模拟,或使用ng-mocks库。 -
是的,我刚刚发现有一个顶级父组件同时使用了这两个组件,即我正在为其编写测试用例的父组件和第二个测试失败的父组件跨度>
-
嘿@dallows:我已经弄清楚另一个组件受到这个 aComponent 的影响并添加了所需的 tick(2000) 现在所有测试用例失败的问题都已解决,一个新问题是 debug.js :21 错误:1 个计时器仍在队列中。我曾经在另一个组件中使用过 tick(2000) 的地方。 (这也是随机发生的)
标签: angular typescript unit-testing karma-jasmine karma-runner