问题描述
Angular Material 提供用于测试的组件线束,让您可以与其交互await
承诺的组件,像这样:
Angular Material provides component harnesses for testing, which lets you interact with their components by await
ing promises, like this:
it('should click button', async () => {
const matButton = await loader.getHarness(MatButtonHarness);
await matButton.click();
expect(...);
});
但是如果按钮点击触发延迟操作怎么办?通常我会使用 fakeAsync()
/tick()
来处理它:
But what if the button click triggers a delayed operation? Normally I would use fakeAsync()
/tick()
to handle it:
it('should click button', fakeAsync(() => {
mockService.load.and.returnValue(of(mockResults).pipe(delay(1000)));
// click button
tick(1000);
fixture.detectChanges();
expect(...);
}));
但是有什么办法可以在同一个测试中同时做这两项吗?
But is there any way I can do both in the same test?
将 async
函数包装在 fakeAsync()
中给我错误:代码应该在 fakeAsync 区域中运行以调用此函数",大概是因为一旦它完成一个 await
,它不再是我传递给 fakeAsync()
的同一个函数.
Wrapping the async
function inside fakeAsync()
gives me "Error: The code should be running in the fakeAsync zone to call this function", presumably because once it finishes an await
, it's no longer in the same function I passed to fakeAsync()
.
我是否需要做这样的事情——在等待之后启动一个 fakeAsync 函数?或者有更优雅的方式吗?
Do I need to do something like this -- starting a fakeAsync function after the await? Or is there a more elegant way?
it('should click button', async () => {
mockService.load.and.returnValue(of(mockResults).pipe(delay(1000)));
const matButton = await loader.getHarness(MatButtonHarness);
fakeAsync(async () => {
// not awaiting click here, so I can tick() first
const click = matButton.click();
tick(1000);
fixture.detectChanges();
await click;
expect(...);
})();
});
推荐答案
fakeAsync(async () => {...})
是一个有效的结构.
此外,Angular Material 团队是 明确测试此场景.
Moreover, Angular Material team is explicitly testing this scenario.
it('should wait for async operation to complete in fakeAsync test', fakeAsync(async () => {
const asyncCounter = await harness.asyncCounter();
expect(await asyncCounter.text()).toBe('5');
await harness.increaseCounter(3);
expect(await asyncCounter.text()).toBe('8');
}));
这篇关于角度测试:使用 fakeAsync 和 async/await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!