异步/等待(async/await)和异步/fixture.whenStable在Angular中的区别

3

我想了解在 Angular 框架测试中处理异步调用的这两种方法的区别:

  • 第一种是使用 Jasmine 方法的 async/await
  • 第二种是使用 Angular 方法的 async/fixture.whenStable

它们相似吗?如果不是,它们有什么区别,我应该在什么情况下使用其中一种而不是另一种?

1个回答

4
< p> async / await 的第一种方法是使用原始的 JavaScript,您希望以异步方式运行函数,并且可以在继续下一行之前等待承诺。
it('it block in an async await way', async(done) => {
   await waitForThisFunctionThatReturnsAPromiseBeforeCarringForward();
   // do something, make assertions
   const x = await getXFromAPromise(); // wait for getXFromAPromise() function to return the promise
// and assign the results to x
   // do something, make assertions
   done(); // call done to ensure you have run through the whole it block and tell Jasmine you're done
});

fixture.whenStable 基本上等待堆栈中所有的 Promise 都被解析后才继续执行断言。

it('demonstration of fixture.whenStable', async(done) => {
   // do some actions that will fire off promises
   await fixture.whenStable(); // wait until all promises in the call stack have been resolved
   // do some more assertions
   done(); // call done to tell Jasmine you're done with this test.
});

done回调函数是可选的,但我使用它来确保更好的工程质量(确保它遍历整个 it 块)。

编辑====================

要处理可观察对象,我使用两种方法。

async/awaittaketoPromise操作符一起使用,其中您接收第一个发射并将其转换为Promise。可以添加其他运算符,如filter,以忽略在take(1)之前的某些发射。

import { take } from 'rxjs/operators';
......
it('should do xyz', async done => {
  const x = await component.observable$.pipe(take(1)).toPromise();
  expect(x).toBe(....);
  done();
});

另一种方法是使用 done 回调函数进行订阅。
it('should do xyz', done => {
  component.observable$.subscribe(result => {
    expect(result).toBe(...);
    // call done here to ensure the test made it within the subscribe
    // and did the assertions and to let Jasmine know you're done with the tests
    done();
  });
});

谢谢你的回答!我想知道这两种方法是可用于Observables还是只能用于Promises? - Houssem Khaldi
这些方法只用于处理 promises。我已经编辑了我的答案,向你展示我如何处理 observables。 - AliF50
2
感谢您的详细解释!它对我很有帮助。 - Houssem Khaldi
那么我在我的测试中是应该使用普通的async/await还是waitForAsync呢?这真的有关系吗? - Red2678
1
@Red2678 这并不重要,这只是个人偏好的问题。 - AliF50

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接