我有这样的AWS lambda函数:
exports.handler = function(event, context, callback) {
const myModel = exports.deps().myModel;
return tools.checkPermission(event)
.then((id) => myModel.create(JSON.parse(event.body), id))
.then((campaign) =>
tools.handleAPIResponse(
callback,
data,
201,
Object.assign({Location: event.path + '/' + data.id,}, tools.HEADERS)
)
).catch(err => tools.handleAPIError(callback, err));
};
我正在使用sinon.js编写一个测试用例,目的只是通过对所有函数进行存根检查来检查lambda函数中的所有方法。喜欢
myModel.create
tools.checkPermission
tools.handleAPIError
tools.handleAPIResopnse
我正在像这样测试和测试:
it('should call all functions ', () => {
const event = {};
createMyStub = sinon.stub(myModel, 'create');
createMyStub.withArgs(sinon.match.any).returns(Promise.resolve('Hello'));
const checkPermission = sinon.stub(tools, 'checkPermission');
checkPermission.withArgs(sinon.match.any).returns(Promise.resolve('user'));
const handleAPIResponse = sinon.stub(tools, 'handleAPIResponse');
handleAPIResponse.withArgs(sinon.match.any).returns('Done');
const callback = sinon.spy();
API.handler(event, {}, callback);
expect(checkPermission.called).to.be(true);
expect(handleAPIResponse.called).to.be(true);
expect(createMyStub.called).to.be(true);
createMyStub.restore();
checkPermission.restore();
handleAPIResponse.restore();
});
但是我没有得到预期的结果。另外,当我不对tools.handleAPIResponse进行存根处理时,如何查看回调的内容,并期望在回调中获得实际结果。
答案 0 :(得分:0)
在这部分中,我发现了您测试中的一个关键错误
API.handler(event, {}, callback);
该函数是异步函数,因此我们必须将其称为promise,例如
await API.handler(event, {}, callback);
或者
API.handler(event, {}, callback).then(....)
我更喜欢前一种方法。而且还可以改进部分测试,例如使用sinon.resolves
和sinon.restore
如下:
it('should call all functions ', async () => { // specify `async`
const event = {};
createMyStub = sinon.stub(myModel, 'create');
createMyStub.withArgs(sinon.match.any).resolves('hello'); // using `resolves`
const checkPermission = sinon.stub(tools, 'checkPermission');
checkPermission.withArgs(sinon.match.any).resolves('user')
const handleAPIResponse = sinon.stub(tools, 'handleAPIResponse');
handleAPIResponse.withArgs(sinon.match.any).returns('Done');
const callback = sinon.spy();
await API.handler(event, {}, callback); // specify `await`
expect(checkPermission.called).to.be(true);
expect(handleAPIResponse.called).to.be(true);
expect(createMyStub.called).to.be(true);
sinon.restore(); // this is sufficient in latest version of sinon, no need to restore on all methods
});
关于您要检查回调的问题,也许我们可以使用sinon.calledWith
例如:
expect(handleAPIResponse.calledWith(callback, ...).to.be(true);
参考:
希望有帮助