我已经看过很多关于如何在单元测试中使用async / await的文章,但我的需求恰恰相反。
如何为使用async / await的方法编写测试?
我的规范在等待' 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。
答案 0 :(得分:3)
承诺的.then
会被重载以处理承诺或值,await
是调用then
的语法糖。
因此没有理由要求你的间谍返回一个承诺,甚至一个价值。完全返回,即使undefined
,也会触发await
触发,并启动async
功能的剩余部分。
我相信你的问题是你在尝试测试它所做的事情之前,你不是在等待doSomething
承诺解决。这样的事情可以让你在球场上更多。
it('should call processResp() with proper arguments', async function () {
await sut.doSomething({});
// ...
});
答案 1 :(得分:0)
Jasmine有Asynchronous Support。您可以找到解决方案。
就个人而言,我认为你根本不应该测试这些方法。
测试状态表示我们正在验证测试中的代码是否返回了正确的结果。
测试互动意味着我们正在验证正在测试的代码是否正确调用某些方法。
在大多数情况下,测试状态更好。
在你的例子中,
async doSomething(reqObj) {
try {
const val = await this.otherCall(reqObj);
return this.processResp(val);
}
}
只要其他电话& processResp很好地适用于单元测试。
e2e测试应该涵盖某些内容。
了解更多相关信息