简体   繁体   English

如何使用Sinon存根“包装器”函数?

[英]How to stub a “wrapper” function using Sinon?

I'm setting up a Lambda function (node.js) and for example's sake, we'll keep it minimal. 我正在设置Lambda函数(node.js),举例来说,我们将其保持在最小限度。

module.exports = (event, context, callback) {
  console.log("hello world")
}

However, I've created a function to wrap the lambda function that allows me to perform some functions that are required before each Lambda executes (I have a collection of Lambda functions that are wired up using their Serverless Application Model (SAM) ). 但是,我创建了一个包装lambda函数的函数,该函数允许我执行每个Lambda执行之前所需的一些功能(我收集了一组Lambda函数,这些函数使用其无服务器应用程序模型(SAMless )进行了连接。 It also allows me to consolidate some of the logging and error handling across each function. 它还使我可以整合每个函数中的一些日志记录和错误处理。

// hook.js
const connect = fn => (event, context, callback) => {
  someFunction()
    .then(() => fn(event, context, callback))
    .then(res => callback(null, res))
    .catch(error => {
      // logging
      callback(error)
    })
}

module.exports = { connect }

// index.js
const Hook = require("./hook")

exports.handler = Hook.connect((event, context, callback) => {
  console.log("hello world")
})

The logic is working well and Lambda is processing it successfully. 逻辑运行良好,Lambda正在成功处理它。 However, I'm trying to stub this Hook.connect function using SinonJS and in need of some guidance. 但是,我试图使用SinonJS对这个Hook.connect函数进行存根,并且需要一些指导。

I simply want to stub it to return a resolved promise, that way we can proceed to handle the code within each Lambda function ( fn(event, context, callback) ). 我只是想对它进行存根返回一个已解决的Promise,这样我们就可以继续处理每个Lambda函数( fn(event, context, callback) )中的代码。

const sinon = require("sinon")
const Hook = require("./hook")
const { handler } = require("./index")
const event = {} // for simplicity sake
const context = {} // for simplicity sake
const callback = {} // for simplicity sake

describe("Hello", () => {
  let connectStub

  beforeEach(() => {
    connectStub = sinon.stub(Hook, "connect").callsFake()

  afterEach(() => {
    connectStub.restore()
  })

  it("works", () => {
    const results = handler(event, context, callback)
    // assert
  })
})

I've tried a few different methods, from the basic, sinon.stub(Hook, "connect") , to the more complicated where I'm trying to stub private functions inside of the hook.js file using rewire . 我已经尝试了一些不同的方法,从基础, sinon.stub(Hook, "connect")到更复杂的地方,我想存根的内部私有函数hook.js使用文件重新布线

Any help would be appreciated -- thank you in advance. 任何帮助将不胜感激-预先感谢您。

Here is a working test: 这是一个工作测试:

const sinon = require('sinon');
const Hook = require('./hook');

const event = {}; // for simplicity sake
const context = {}; // for simplicity sake
const callback = {}; // for simplicity sake

describe('Hello', () => {

  let handler, connectStub;
  before(() => {
    connectStub = sinon.stub(Hook, 'connect');
    connectStub.callsFake(fn => (...args) => fn(...args));  // create the mock...
    delete require.cache[require.resolve('./index')];  // (in case it's already cached)
    handler = require('./index').handler;  // <= ...now require index.js
  });

  after(() => {
    connectStub.restore();  // restore Hook.connect
    delete require.cache[require.resolve('./index')];  // remove the modified index.js
  });

  it('works', () => {
    const results = handler(event, context, callback);  // it works!
    // assert
  });
});

Details 细节

index.js calls Hook.connect to create its exported handler as soon as it runs , and it runs as soon as it is required ... index.js 在运行时立即调用Hook.connect来创建其导出的handler ,并在required立即运行...

...so the mock for Hook.connect needs to be in place before index.js is required : ......所以对于模拟Hook.connect需要在发生之前 index.jsrequired

Node.js caches modules , so this test also clears the Node.js cache before and after the test to ensure that index.js picks up the Hook.connect mock, and to ensure that the index.js with the mocked Hook.connect is removed from the cache in case the real index.js is needed later. Node.js的缓存模块 ,因此本次测试还将清除Node.js的缓存之前该试验后,保证index.js拿起Hook.connect模拟,并确保index.js与嘲笑Hook.connect是从缓存中删除 ,以防以后需要真正的index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM