2017-03-01 39 views
0

我有一些控制器/路由用來處理用戶註冊:如何模擬一個import express.js 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 
    }); 
    ... 

我想測試User時調用正確的ARGS。

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: '[email protected]', 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進口。

如何模擬controllers/user.js中導入的User

回答

1

你可以用這個proxyquire lib(https://github.com/thlorenz/proxyquire)。使用的

實施例:

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