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

Dan*_*anH 0 mocking node.js coffeescript

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我得到的错误TypeError: Cannot read property 'should' of undefined是我确认的,因为我的模拟没有按照我的意愿进行注册.

我认为问题是require(../../modules/fixture/controllers.js)test.tests(app, db, config)调用之前发生的问题,因此已经创建了需要缓存.

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

Lou*_*uis 8

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

mockery.enable({ useCleanCache: true });
Run Code Online (Sandbox Code Playgroud)

使用此选项,在启用模拟之前刷新模块缓存.