Mockery没有嘲笑以前需要的模块?

时间:2014-03-24 16:07:57

标签: node.js coffeescript mocking

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)之前发生了,因此已经创建了需要缓存。

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

1 个答案:

答案 0 :(得分:8)

我在过去使用它来摆脱我在加载模块之前加载的模块:

mockery.enable({ useCleanCache: true });

使用此选项,在启用嘲弄之前cache of modules is flushed