问题描述
在 Angular 2 中进行测试时,您什么时候使用 TestBed 中的异步函数?
When do you use the async function in the TestBed when testing in Angular 2?
你什么时候用这个?
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyModule],
schemas: [NO_ERRORS_SCHEMA],
});
});
你什么时候用这个?
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyModule],
schemas: [NO_ERRORS_SCHEMA],
});
}));
任何人都可以启发我吗?
Can anyone enlighten me on this ?
推荐答案
async
将不允许下一个测试开始,直到 async
完成其所有任务.async
所做的是将回调包装在一个 Zone 中,在该区域中跟踪所有异步任务(例如 setTimeout
).一旦所有异步任务完成,async
就完成了.
async
will not allow the next test to start until the async
finishes all its tasks. What async
does is wrap the callback in a Zone, where all asynchronous tasks (e.g. setTimeout
) are tracked. Once all the asynchronous tasks are complete, then the async
completes.
如果你曾经在 Angular 之外使用过 Jasmine,你可能已经看到 done
被传递给回调
If you have ever worked with Jasmine outside out Angular, you may have seen done
being passed to the callback
it('..', function(done) {
someAsyncAction().then(() => {
expect(something).toBe(something);
done();
});
});
这里是原生的 Jasmine,我们告诉 Jasmine 这个测试应该延迟完成,直到我们调用 done()
.如果我们没有调用 done()
而是这样做:
Here, this is native Jasmine, where we tell Jasmine that this test should delay completion until we call done()
. If we didn't call done()
and instead did this:
it('..', function() {
someAsyncAction().then(() => {
expect(something).toBe(something);
});
});
测试会在预期之前完成,因为承诺会在测试执行完同步任务之后解决.
The test would complete even before the expectation, because the promise resolves after the test is finished executing the synchronous tasks.
使用 Angular(在 Jasmine 环境中),当我们使用 async
时,Angular 实际上会在幕后调用 done
.它会跟踪Zone中所有的异步任务,当它们都完成后,会在后台调用done
.
With Angular (in a Jasmine environment), Angular will actually call done
behind the scenes when we use async
. It will keep track of all the asynchronous tasks in the Zone, and when they are all finished, done
will be called behind the scenes.
在您使用 TestBed
配置的特殊情况下,您通常会在想要 compileComponents
时使用它.我很少遇到我不得不调用它的情况
In your particular case with the TestBed
configuration, you would use this generally when you want to compileComponents
. I rarely run into a situation in which I would have to call it otherwise
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyModule],
schemas: [NO_ERRORS_SCHEMA],
})
.compileComponent().then(() => {
fixture = TestBed.createComponent(TestComponent);
});
}));
当测试一个使用templateUrl
的组件时(如果你没有使用webpack),那么Angular需要发出一个XHR请求来获取模板,所以组件的编译是异步的.所以我们应该等到它解决了再继续测试.
When testing a component that uses templateUrl
(if you are not using webpack), then Angular needs to make an XHR request to get the template, so the compilation of the component would be asynchronous. So we should wait until it resolves before continuing testing.
这篇关于Angular 2 测试 - 异步函数调用 - 何时使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!