我想测试这个组件
describe('Test for check if window dissapeard', () => {
let component: DismissMockedComponent;
let fixture: ComponentFixture<DismissMockedComponent>;
beforeEach(() => {
fixture = TestBed.createComponent(DismissMockedComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('Check if window dissapeard after dissmiss time', () => {
let delayTime = 3000;
spyOn(component, "onAfterDelayTime");
component.dismissible = true;
component.dismissTimer = delayTime;
fixture.detectChanges();
setTimeout(() => {
fixture.detectChanges();
expect(component.onAfterDelayTime).toHaveBeenCalled();
}, delayTime);
});
});
和非常简单的模拟组件
@Component({
template: '<my-inform-window (afterDelayTime)="onAfterDelayTime()"></my-inform-window>'
})
class DismissMockedComponent {
delayTime: number;
onAfterDelayTime(){
console.log('this function was triggered after delay time')
}
}
我收到一个错误
Async function did not complete within 5000ms
我会补充一点,当我将解雇时间设置为 1000 毫秒或 2000 毫秒时,所有工作都正确......
知道问题出在哪里吗?
使用 FakeAsync 测试时间延迟功能
it('Check if window disappeared after dismiss time', fakeAsync(() => {
const delayTime = 3000;
spyOn(component, "onAfterDelayTime");
component.dismissible = true;
component.dismissTimer = delayTime;
fixture.detectChanges();
tick(delayTime); // Simulate the passage of delayTime milliseconds
fixture.detectChanges();
expect(component.onAfterDelayTime).toHaveBeenCalled();
flush(); // Ensure that no more tasks are left in the queue
}));