async/await 和 async/fixture.whenStable 在 Angular 中的区别

Difference between async/await and async/fixture.whenStable in Angular

我在测试的时候想知道Angular框架中这两种异步调用处理方式的区别:

它们相似吗?如果不是,有什么区别,什么时候我应该使用一个而不是另一个?

async/await 的第一种方法是 stock 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 基本上等待堆栈中的所有承诺都得到解决,然后再进行断言。

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 运算符,您在其中获取第一个发射并将其转换为承诺。随意添加其他运算符,例如 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();
});

另一种方法是 subscribedone 回调

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();
  });
});