【问题标题】:Difference between async/await and async/fixture.whenStable in AngularAngular 中 async/await 和 async/fixture.whenStable 之间的区别
【发布时间】:2020-09-16 03:45:15
【问题描述】:

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

  • 第一个使用 jasmine 方法 async/await
  • 第二个使用 Angular 方法 async/fixture.whenStable

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

【问题讨论】:

    标签: angular unit-testing asynchronous async-await karma-jasmine


    【解决方案1】:

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

    【讨论】:

    • 感谢您回答我!我想知道这两种方法是否可用于 Observables 或仅用于 Promises?
    • 这些方法仅用于承诺。我已经编辑了我的答案,以向您展示我如何处理 observables。
    • 感谢详细的解释!对我帮助很大
    • 那么我应该在测试中使用 vanilla async/await 还是 waitForAsync 呢?这真的很重要吗?
    • @Red2678 没关系,这是偏好问题。
    猜你喜欢
    • 2015-01-06
    • 2016-07-11
    • 1970-01-01
    • 2021-09-20
    • 2019-10-08
    • 2012-05-04
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    相关资源
    最近更新 更多