首页 > 解决方案 > Angular 中 async/await 和 async/fixture.whenStable 之间的区别

问题描述

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

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

标签: angularunit-testingasynchronousasync-awaitkarma-jasmine

解决方案


第一种方法async/await是库存 JavaScript,您希望在其中异步运行该函数,并且您可以在继续到下一行之前等待 Promise。

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 块)。

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

为了处理 observables,我使用了两种方法。

async/await使用takeandtoPromise运算符,您在其中进行第一次发射并将其转换为承诺。随意添加其他运算符,例如filtertake(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();
});

另一种方法是subscribe使用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();
  });
});

推荐阅读