【发布时间】:2019-02-15 10:29:00
【问题描述】:
我的 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 时,如何查看回调的内容,并期望回调中的实际结果。
【问题讨论】:
-
你的测试结果如何?
标签: javascript node.js unit-testing mocha.js sinon