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

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

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

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

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

最佳答案

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 基本上等待堆栈中的所有 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 block )。

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

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

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

关于angular - Angular 中 async/await 和 async/fixture.whenStable 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62071276/

相关文章:

angular - 模板更改@Prop() 检测

unit-testing - 如何使用 CodeIgniter 轻松进行单元测试?

javascript - Vue/Vuex - 模块二依赖模块一,模块一从服务器获取数据

Angular 4 - ngModelChange 在两个选择表单绑定(bind)期间抛出无法读取未定义的属性 '...'

Angular 2 路由器,错误 : Cannot activate an already activated outlet

unit-testing - Vue.js 过滤器和测试

java - 用 java 编写单元测试

asp.net-mvc - 如何在 MVC 3 中正确进行长轮询

ios - 快速从调用者到被调用者的回调函数

angular - 从 Angular 发送数据时,web-api POST 主体对象始终为 null