angular - Angular 中 async/await 和 async/fixture.whenStable 之间的区别
问题描述
我想知道这两种方法在测试时处理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
所有承诺在继续断言之前得到解决。
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
使用take
andtoPromise
运算符,您在其中进行第一次发射并将其转换为承诺。随意添加其他运算符,例如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();
});
另一种方法是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();
});
});
推荐阅读
- python - 从 csv 打开时按顺序动态命名数据帧 - Python/Pandas
- python - 如何创建投票系统来定义没有图书馆的会议的最佳日期
- python - 如何仅打印 idx, val 的第一个值
- powershell - 如何在不写入控制台的情况下写入日志文件
- python - 使用 jax 数组索引到 numpy 数组:错误的错误消息
- android - 如何在空对象引用错误上清除空对象引用上的 BitmapDrawable.getBitmap()'
- visual-studio - VS 代码上的 ErrNo2
- android - Android自动填充电话号码未出现,仅显示“密码”
- django - save() 接受 1 个位置参数,但给定 2 个 djnago allauth resetpassword 形式
- rust - 使用 transmute 的递归数据结构的零成本构建器模式。这安全吗?有更好的方法吗?