Мне нравится использовать async(done)
и ждать выполнения обещаний, прежде чем их утверждать.
it('should do something', async(done) => {
// given
const { comp, el, fixture } = setup();
// when
fixture.detectChanges();
comp.doSomethingAsync(); // Trigger asynchronous code
await fixture.whenStable();
// your assertions
done();
});
Однако в вашем случае, поскольку вы используете setTimeout
из 5 с, вы можете сохранить 5 секунд, используя fakeAsync
и tick
. Тик подделывает время.
it('should do something', fakeAsync(() => {
// given
const { comp, el, fixture } = setup();
// when
fixture.detectChanges();
comp.doSomethingAsync(); // Trigger asynchronous code
tick(5000); // Make 5 seconds pass instantaneously
// your assertions
}));
================================ ============ Теперь вы говорите, чтобы не запускать код asynchronous
после завершения теста. Может быть, вы можете сделать:
// wait for the promises to resolve before going to the next it test
afterEach(async(done) => { await fixture.whenStable(); done(); });
Если они setTimeout
, я бы очистил тайм-ауты в ngOnDestroy
, чтобы они не преследовали вас в будущем.