【问题标题】:unit testing express middleware单元测试快速中间件
【发布时间】:2021-03-25 11:48:22
【问题描述】:

我的快递应用中有以下中间件功能,

const { getEmployerId } = require("./employerApi");

const setEmployerDetails = (employerId) => {
    return (req, res, next) => {
        getEmployerId(req, res, next, employerId);
    }
}

module.exports = setEmployerDetails

我想对这个中间件进行单元测试,但我不确定如何,该函数基本上返回 API 返回的任何内容,API 已经过单元测试。我将如何使用 chai 之类的东西对这个函数进行单元测试?

到目前为止,

describe('setEmployerDetails`, () => {
   it('should be a function', () => expect(setEmployerDetails).to.be.a('function'));
   it('should take 1 argument', () => expect(setEmployerDetails.length).to.equal(1));
});`

【问题讨论】:

    标签: javascript node.js express unit-testing chai


    【解决方案1】:

    你应该存根getEmployerId函数使用Link Seams。然后,照常进行测试。

    例如

    mw.js:

    const { getEmployerId } = require('./employerApi');
    
    const setEmployerDetails = (employerId) => {
      return (req, res, next) => {
        getEmployerId(req, res, next, employerId);
      };
    };
    
    module.exports = setEmployerDetails;
    

    mw.test.js:

    const proxyquire = require('proxyquire');
    const sinon = require('sinon');
    
    describe('66798873', () => {
      it('should pass', () => {
        const getEmployerId = sinon.stub();
        const setEmployerDetails = proxyquire('./mw', {
          './employerApi': { getEmployerId },
        });
        const mReq = {};
        const mRes = {};
        const mNext = sinon.stub();
        setEmployerDetails(123)(mReq, mRes, mNext);
        sinon.assert.calledWithExactly(getEmployerId, {}, {}, mNext, 123);
      });
    });
    

    单元测试结果:

      66798873
        ✓ should pass (2712ms)
    
    
      1 passing (3s)
    
    ----------------|---------|----------|---------|---------|-------------------
    File            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------------|---------|----------|---------|---------|-------------------
    All files       |     100 |      100 |     100 |     100 |                   
     employerApi.js |       0 |        0 |       0 |       0 |                   
     mw.js          |     100 |      100 |     100 |     100 |                   
    ----------------|---------|----------|---------|---------|-------------------
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      相关资源
      最近更新 更多