Angular 避免在测试完成后运行beign中的异步代码
我们的Jasmine测试套件每天都在变得越来越脆弱,因为测试完成后会运行异步代码 例如: 代码: @组成部分 导出类MyComponent{ 剂量{ 设置超时=>{ 一些在最上面的东西; }, 5000; } } 测试: 它“应该做点什么”,=>{ component.doSomething;我喜欢使用asyncdone,并在断言承诺之前等待承诺得到解决Angular 避免在测试完成后运行beign中的异步代码,angular,jasmine,Angular,Jasmine,我们的Jasmine测试套件每天都在变得越来越脆弱,因为测试完成后会运行异步代码 例如: 代码: @组成部分 导出类MyComponent{ 剂量{ 设置超时=>{ 一些在最上面的东西; }, 5000; } } 测试: 它“应该做点什么”,=>{ component.doSomething;我喜欢使用asyncdone,并在断言承诺之前等待承诺得到解决 it('should do something', async(done) => { // given const
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为5s,所以您可以通过使用fakeAsync和tick来节省5s。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
}));
=============================================
现在您要说的是避免异步代码在测试完成后运行。也许您可以这样做:
// wait for the promises to resolve before going to the next it test
afterEach(async(done) => { await fixture.whenStable(); done(); });
如果他们设置了超时,我会清除Ngondestory中的超时,这样他们就不会在将来困扰你。使用承诺。有些事情不需要如此迟钝