2016-12-11 72 views
0

所以我有一個節點模塊,如:單元測試/懲戒貓鼬型號興農

let mongoose = require('mongoose'), 
    User = mongoose.model('User'); 

module.exports = (req, res, next) => { 
    User.findById(req.user) 
    .then(user => { 
     req.body.user = user._id; 
     req.body.company = user.company; 
     next(); 
    }, err => { 
     req.send(400, err); 
    }); 
}; 

因此,在這種情況下,我想,以確保正確的東西附着在req.body。那麼,我該如何去嘲弄User函數呢?我必須首先加載模型,以便在調用mongoose.model之前,此代碼不會引發錯誤,因此可能與實際存根全球require存根有關?感謝您的任何建議!

回答

0

所以,我剛剛發現了proxyquirehttps://www.npmjs.com/package/proxyquire它就像天堂一般,爲我最輝煌的「啊哈」時刻開啓了光芒。在嘗試使用它們之前,不再需要在貓鼬中加載模型!

以模擬貓鼬的代碼看起來是這樣的:

const proxyquire = require('proxyquire'), 
    expect = require('chai').expect, 
    Promise = require('bluebird'), 
    _ = require('lodash'), 
    USERID = 'abc123', 
    COMPANY = 'Bitwise', 
    mongooseStub = { 
    mongoose: { 
     model: (name, schema) => ({ 
     findById:() => { 
      return new Promise((resolve, reject) => { 
      resolve({_id: USERID, company: COMPANY}); 
      }); 
     } 
     }) 
    } 
    }, 
    attachUser = proxyquire('../lib/users/attach-user', mongooseStub); 

這將有效地加載attach-user模塊,而磕碰出mongoose.model函數返回的東西我可以控制的。然後,我的測試的其餘部分只是調用模塊函數,並可以按預期做出斷言。