【发布时间】:2018-06-29 00:40:53
【问题描述】:
我看过很多关于如何在单元测试中使用 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。
【问题讨论】:
标签: angularjs unit-testing jasmine ecmascript-2017