Proxyquire调用原始文件而不是存根

时间:2016-09-08 10:37:39

标签: node.js mocha proxyquire

您好我试图使用proxyquire在我的控制器中模拟一个模型。但出于某种原因,当尝试注入模拟时,原始文件被调用。

这就是控制器内部需要我的模型的方法:

var Product = require('./product.model');

这就是我试图抄袭模型的方式

  var proxyquire = require('proxyquire').noCallThru().noPreserveCache();
  var productsStub = {findAsync: sinon.stub()};
  productsStub.findAsync.resolves(mockProducts);
  var mockProducts = [{_id:'0001',title: 'title', price: 123, description: 'le description'}];
  var productController = proxyquire('./product.controller',{'./product.model':productsStub});

但是当我运行测试时出现此错误

Running "mochaTest:unit" (mochaTest) task
>> Mocha exploded!
>> OverwriteModelError: Cannot overwrite `Product` model once compiled.
>>     at Mongoose.model (/Users/victor/Documents/projects/estudo/mean/meanshop/node_modules/mongoose/lib/index.js:360:13)
>>     at Object.<anonymous> (/Users/victor/Documents/projects/estudo/mean/meanshop/server/api/product/product.model.js:15:27)
>>     at Module._compile (module.js:409:26)
>>     at normalLoader (/Users/victor/Documents/projects/estudo/mean/meanshop/node_modules/babel-core/lib/api/register/node.js:199:5)
>>     at Object.require.extensions.(anonymous function) [as .js] (/Users/victor/Documents/projects/estudo/mean/meanshop/node_modules/babel-core/lib/api/register/node.js:216:7)
>>     at Module.load (module.js:343:32)
>>     at Function.Module._load (module.js:300:12)
>>     at Module.require (module.js:353:17)
>>     at require (internal/module.js:12:17)
>>     at Object.<anonymous> (/Users/victor/Documents/projects/estudo/mean/meanshop/server/api/product/product.model.spec.js:1:15)
>>     at Module._compile (module.js:409:26)
>>     at normalLoader (/Users/victor/Documents/projects/estudo/mean/meanshop/node_modules/babel-core/lib/api/register/node.js:199:5)
>>     at Object.require.extensions.(anonymous function) [as .js] (/Users/victor/Documents/projects/estudo/mean/meanshop/node_modules/babel-core/lib/api/register/node.js:216:7)
>>     at Module.load (module.js:343:32)
>>     at Function.Module._load (module.js:300:12)
>>     at Module.require (module.js:353:17)
>>     at require (internal/module.js:12:17)
>>     at /Users/victor/Documents/projects/estudo/mean/meanshop/node_modules/mocha/lib/mocha.js:220:27
>>     at Array.forEach (native)
>>     at Mocha.loadFiles (/Users/victor/Documents/projects/estudo/mean/meanshop/node_modules/mocha/lib/mocha.js:217:14)
>>     at MochaWrapper.run (/Users/victor/Documents/projects/estudo/mean/meanshop/node_modules/grunt-mocha-test/tasks/lib/MochaWrapper.js:51:15)
>>     at /Users/victor/Documents/projects/estudo/mean/meanshop/node_modules/grunt-mocha-test/tasks/mocha-test.js:86:20

我的问题是,如果理论上不会调用原始的products.model.js模块,我会得到这个。

1 个答案:

答案 0 :(得分:1)

proxyquire不会存储未列出的模块,并且它们将照常使用,因此 看起来你在product.controller中有更多的依赖项,而且它们通常都是必需的。

除了为proxyquire提供完整存根之外,我找不到解决此问题的好方法。