如何模拟导入express.js supertest?

时间:2017-03-01 19:50:36

标签: node.js unit-testing express sinon supertest

我有一些处理用户注册的控制器/路由:

controllers/user.js

const User = require('../models/User');       // What I want to mock!
...
/**
 * POST /signup
 * Create a new local account.
 */
exports.postSignup = (req, res, next) => {
  ...
  const user = new User({
    email: req.body.email,
    password: req.body.password
  });
  ...

我想测试使用正确的args调用User

test/userIntegrationTest.js

const request = require('supertest');
const app = require('../app.js');
const sinon = require('sinon');
const User = require('../models/User');

describe('POST /signup', () => {
  it('should create user with valid email', (done) => {
    const formdata = {email: 'te.st@gmail.com', password: 'asdf'};

    const UserMock = sinon.mock(User);      // This mock doesn't do what I want!

    request(app)
      .post('/signup')
      .send(formdata)
      .expect(200)
      .end(function(res) {
        expect(UserMock.calledOnce).to.be.true;
        expect(UserMock.calledWith(formdata));
      })
  });
});

我希望从控制器调用UserMock但是这个模拟似乎只模拟User中导入的userIntegrationTest.js模型。

如何模拟User中导入的controllers/user.js

1 个答案:

答案 0 :(得分:1)

您可以使用此 proxyquire lib(https://github.com/thlorenz/proxyquire)。

使用示例:

var apiCallsMock = require('./apiCallsMock');
var messageParser  = proxyquire('../messageParser', {'./apiCalls': apiCallsMock});
var app = proxyquire('../index', {'./messageParser': messageParser});