gpt4 book ai didi

Angular Testing : using fakeAsync with async/await

转载 作者:行者123 更新时间:2023-12-03 15:13:47 32 4
gpt4 key购买 nike

Angular Material 提供 component harnesses用于测试,它允许您通过 await 与其组件交互ing promise ,像这样:

  it('should click button', async () => {
const matButton = await loader.getHarness(MatButtonHarness);
await matButton.click();
expect(...);
});

但是如果按钮点击触发了延迟操作呢?通常我会使用 fakeAsync()/ tick()处理它:
  it('should click button', fakeAsync(() => {
mockService.load.and.returnValue(of(mockResults).pipe(delay(1000)));
// click button
tick(1000);
fixture.detectChanges();
expect(...);
}));

但是有什么办法可以在同一个测试中同时做这两项吗?

包装 async内部函数 fakeAsync()给我“错误:代码应该在 fakeAsync 区域中运行以调用此函数”,大概是因为一旦它完成了 await ,它不再在我传递给 fakeAsync() 的同一个函数中.

我是否需要做这样的事情——在等待之后启动一个 fakeAsync 函数?或者有更优雅的方式吗?
  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(...);
})();
});

最佳答案

你不应该需要一个(真实的)asyncfakeAsync ,至少可以控制模拟的时间流。 fakeAsync点是让你更换await s 与 tick/flush .现在,当您真正需要该值时,我认为您无法恢复到 then , 像这样:

  it('should click button', fakeAsync(() => {
mockService.load.and.returnValue(of(mockResults).pipe(delay(1000)));
const resultThing = fixture.debugElement.query(By.css("div.result"));
loader.getHarness(MatButtonHarness).then(matButton => {
matButton.click();
expect(resultThing.textContent).toBeFalsy(); // `Service#load` observable has not emitted yet
tick(1000); // cause observable to emit
expect(resultThing.textContent).toBe(mockResults); // Expect element content to be updated
});
}));
现在,因为您的测试主体函数在对 fakeAsync 的调用中,它应该 1) 在所有创建的 promise (包括由 getHarness 返回的 promise )都得到解决之前,不允许测试完成,并且 2) 如果有任何挂起的任务,则测试失败。
(顺便说一句,我认为在第二个 fixture.detectChanges() 之前您不需要 expect,如果您使用的是 async 管道和您的服务返回的 Observable,因为 async 管道明确地戳了所有者的每当其内部订阅触发时更改检测器。不过,我很想知道我是否错了。)

关于 Angular Testing : using fakeAsync with async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61739584/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com