首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sinon和mocha -sinon私有依赖项

sinon和mocha -sinon私有依赖项
EN

Stack Overflow用户
提问于 2018-03-04 21:25:34
回答 2查看 244关注 0票数 0

我有一个node express应用程序,我正在用mocha,chai和sinon为它写一些测试。我有一个包含端点处理程序的模块。它大致看起来像这样:

代码语言:javascript
复制
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是一个内部依赖项。需要做些什么才能使其正常工作?

谢谢。

EN

回答 2

Stack Overflow用户

发布于 2018-03-12 09:55:05

你有没有试过在你的测试中去掉它?如果由于导出数据库的方式导致正常的存根不起作用,请尝试rewire:

代码语言:javascript
复制
const sinon = require('sinon');
const rewire = require('rewire');

var myModule = rewire('./myModule');

describe('myModule', () => {
    it('should test myModule', () => {
        let fake = {
            save: () => {
                console.log('stub save')
                //return whatever you want 
            }
        }

        myModule.__set__('db', fake);
        //db.save in your module should now call the fake function
    });
})

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

票数 0
EN

Stack Overflow用户

发布于 2019-12-28 12:49:11

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

例如。

index.js

代码语言:javascript
复制
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

代码语言:javascript
复制
function Factory() {
  const db = {
    save() {},
  };
  return db;
}

module.exports = Factory;

index.spec.js

代码语言:javascript
复制
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" });
    });
  });
});

单元测试结果和覆盖率报告:

代码语言:javascript
复制
  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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49095899

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档