我看过很多关于如何在单元测试中使用 async/await 的文章,但我的需求正好相反。
您如何为使用 async/await 的方法编写测试?
我的规范在“等待”行之后无法访问任何代码。具体来说,规范在两个方面失败了。
1) HelloWorld.otherCall
返回 undefined 而不是我指定的返回值
2) HelloWorld.processResp
永远不会被调用
class HelloWorld {
async doSomething(reqObj) {
try {
const val = await this.otherCall(reqObj);
console.warn(val); // undefined
return this.processResp(val);
}
}
}
describe('HelloWorld test', function () {
let sut = new HelloWorld(); //gross simplification for demo purposes
describe('doSomething()', function () {
beforeEach(function mockInputs() {
this.resp = 'plz help - S.O.S.';
});
beforeEach(function createSpy() {
spyOn(sut, 'otherCall').and.returnValue( $q.resolve(this.resp) );
spyOn(sut, 'processResp');
});
it('should call otherCall() with proper arguments', function () {
//this test passes
});
it('should call processResp() with proper arguments', function () {
sut.doSomething({});
$rootScope.$apply(); //you need this to execute a promise chain..
expect(sut.processResp).toHaveBeenCalledWith(this.resp);
//Expected spy processResp to have been called with [ 'plz help SOS' ] but it was never called.
});
});
});
运行 angular 1.5 和 jasmine-core 2.6。
最佳答案
.then
promise 的重载以处理 promise 或值,和 await
是调用 then
的语法糖.
所以没有理由要求你的 spy 返回一个 promise ,甚至一个值。完全返回,即使 undefined
, 应该触发 await
开火,然后开始剩下的 async
功能。
我相信你的问题是你没有等待 doSomething
promise 在尝试测试它做了什么之前解决。像这样的事情应该会让你更有把握。
it('should call processResp() with proper arguments', async function () {
await sut.doSomething({});
// ...
});
关于angularjs - 如何测试使用 async/await 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48346754/