sinon和mocha - 存根私有依赖

时间:2018-03-04 13:25:34

标签: node.js mocha sinon

我有一个节点表达应用程序,我正在用mocha,chai和sinon为它编写一些测试。我有一个包含端点处理程序的模块。它大致如下:

var db = require('./db-factory)();

module.exports = {
   addUser: function(req, res) {
       if (req.body.deviceID === undefined) {
           res.status(400).json({ error: 'deviceID is missing' });
           return;
       }      

       db.save(req.body, function(err) {
           // return 201 or 500 based on err
       });
   }
}

我想将db.save调用存根以返回201状态,但正如您所见,db是内部依赖性。需要做些什么来使其发挥作用?

感谢。

2 个答案:

答案 0 :(得分:0)

你有没有试过在测试中存根?如果正常的存根因数据导出方式不起作用,请尝试重新连接:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']

})
export class AppComponent {
  myMinVar:Date;
  myMaxVar:Date;

  constructor() { }

  ngOnInit() {
    this.myMaxVar = new Date(2018,2,2);
    this.myMinVar = new Date(2012,2,2);
  }
}

myModule是带有端点的模块。这应该替换myModule中的整个db模块。

答案 1 :(得分:0)

这是使用附加库proxyquire来存根./db-factory模块的单元测试解决方案。

例如

index.js

const db = require("./db-factory")();

module.exports = {
  addUser: function(req, res) {
    if (req.body.deviceID === undefined) {
      res.status(400).json({ error: "deviceID is missing" });
      return;
    }

    db.save(req.body, function(err) {
      if (err) {
        return res.sendStatus(500);
      }
      res.sendStatus(201);
    });
  },
};

./db-factory.js

function Factory() {
  const db = {
    save() {},
  };
  return db;
}

module.exports = Factory;

index.spec.js

const sinon = require("sinon");
const proxyquire = require("proxyquire");

describe("49095899", () => {
  afterEach(() => {
    sinon.restore();
  });
  describe("#addUser", () => {
    it("should save user correctly", () => {
      const dbStub = { save: sinon.stub().yields(null) };
      const handlers = proxyquire("./", {
        "./db-factory.js": sinon.stub().returns(dbStub),
      });
      const mReq = { body: { name: "a", age: 25, deviceID: "1" } };
      const mRes = { status: sinon.stub(), sendStatus: sinon.stub() };
      handlers.addUser(mReq, mRes);
      sinon.assert.calledWith(dbStub.save, mReq.body, sinon.match.func);
      sinon.assert.calledWith(mRes.sendStatus, 201);
    });

    it("should send status 500 if save user failed", () => {
      const mError = new Error("save user error");
      const dbStub = { save: sinon.stub().yields(mError) };
      const handlers = proxyquire("./", {
        "./db-factory.js": sinon.stub().returns(dbStub),
      });
      const mReq = { body: { name: "a", age: 25, deviceID: "1" } };
      const mRes = { status: sinon.stub(), sendStatus: sinon.stub() };
      handlers.addUser(mReq, mRes);
      sinon.assert.calledWith(dbStub.save, mReq.body, sinon.match.func);
      sinon.assert.calledWith(mRes.sendStatus, 500);
    });

    it("should send status 400 if deviceId is missing", () => {
      const handlers = require("./");
      const mReq = { body: { name: "a", age: 25 } };
      const mRes = { status: sinon.stub().returnsThis(), json: sinon.stub() };
      handlers.addUser(mReq, mRes);
      sinon.assert.calledWith(mRes.status, 400);
      sinon.assert.calledWith(mRes.json, { error: "deviceID is missing" });
    });
  });
});

带有覆盖率报告的单元测试结果:

  49095899
    #addUser
      ✓ should save user correctly
      ✓ should send status 500 if save user failed
      ✓ should send status 400 if deviceId is missing


  3 passing (24ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |      100 |       90 |      100 |                   |
 db-factory.js |      100 |      100 |       50 |      100 |                   |
 index.js      |      100 |      100 |      100 |      100 |                   |
 index.spec.js |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/49095899