2014-03-24 57 views
0

views.js嘲笑不嘲笑以前需要的模块?

controllers = require '../../modules/fixture/controllers.js' 
exports.custom = (db) -> 
    (req, res) -> 
    controllers.custom req.body 
     , (result) -> 
     res.json result : result 
     , (error) -> 
     res.json 400, error : error 

test.js

mockery = require "mockery" 

exports.tests = (app, db, config) -> 
    describe '#routes', -> 
    describe '/fixture/custom', -> 
     it 'should return status 400 if no request body was provided', (done) -> 
     request app 
      .post '/fixture/custom' 
      .send 
      body : 
       players : [] 
      .expect 400, done 

    describe '#views', -> 
    describe '#custom', -> 
     controller = 
     custom : (body, success_callback, error_callback) -> 
      console.log "###MOCK CONTROLLER BODY: #{req}" 
      if body 
      success_callback 'result' 
      else 
      error_callback 'error' 
     mockery.enable() 
     mockery.registerAllowable '../../modules/fixture/controllers.js', true 
     mockery.registerMock '../../modules/fixture/controllers.js', controller 

     it 'should return json keyed by result on success callback', (done) -> 
     req = 
      body : true 
     res.json = (response) -> 
      response.result.should.eql 'result' 
      done() 
     custom req, res 

我得到我已经证实是由于我的模拟没有得到注册,因为我想错误TypeError: Cannot read property 'should' of undefined

我在考虑问题是require(../../modules/fixture/controllers.js)发生在调用test.tests(app, db, config)之前,因此require cache已经创建。

不应该mockery.registerAllowable('../../modules/fixture/controllers.js', true)允许我覆盖已经需要的模块吗?在很多测试中,我需要在真实和模拟模块之间切换很多,所以我希望能够“及时”注册mock,而不是在开始时注册mock,例如在实例化我的快速应用程序之前。这可能吗?

回答

8

我已经在过去使用这种摆脱我就装好之前启用嘲弄模块:

mockery.enable({ useCleanCache: true }); 

使用此选项时,cache of modules is flushed使嘲弄之前。

+0

我在Yeoman angular-fullstack项目中遇到了问题。测试运行良好,只有摩卡来自,但'咕噜测试'失败。我用Mockery创建的模拟没有在测试中加载。这显然是由于一些其他测试/设置需要我之前测试的模块,因此它被缓存。对我来说,使用'useCleanCache:true'这个技巧对我来说是个诀窍。 – Raipe