嗨,我正在尝试使用 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 模块,为什么我会得到这个。