Sinon测试检查所有方法都在lambda中调用

问题描述 投票:0回答:1

我有这样的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 sinon
1个回答
0
投票

我在这部分测试中发现了一个重要的错误

API.handler(event, {}, callback);

该函数是异步函数,因此我们必须将其称为承诺,例如

await API.handler(event, {}, callback);

或者

API.handler(event, {}, callback).then(....)

我更喜欢前一种方法。还有一些测试可以像使用sinon.resolvessinon.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);

参考:

希望能帮助到你

© www.soinside.com 2019 - 2024. All rights reserved.