使用proxyquire加载模块时报ENOENT错误,无故检索不存在的src/models路径如何解决
解决方法
根因说明
你报错里的src/models路径并非来自proxyquire的导入逻辑,而是sequelize自动生成的models/index.js文件中的默认配置:该文件默认会扫描src/models目录下的模型文件,你的项目没有src目录,因此触发路径不存在的报错。
另外你的测试代码还存在路径匹配、逻辑不符的问题。
具体修复步骤
- 修正sequelize模型加载路径
打开server/models/index.js文件,找到扫描模型目录的代码行,通常如下:
- 修正sequelize模型加载路径
const modelsPath = path.join(__dirname, 'src', 'models')
修改为当前models目录的实际路径:
const modelsPath = path.join(__dirname, '.')
- 修正proxyquire导入路径
不要用path.resolve('./services/userService.js'),该路径是相对于你执行测试命令的工作目录,和测试文件所在目录的相对规则不一致,直接使用测试文件到业务文件的相对路径即可:
- 修正proxyquire导入路径
// 测试文件在 server/specs/services/,业务文件在 server/services/,相对路径正确 const servicePath = '../../services/userService.js'
proxyquire覆写的key必须和业务文件里的导入路径完全一致,你业务文件里写的是require('../models'),所以覆写的key就必须是'../models',不能修改。
- 修正测试逻辑错误
你的业务文件只导出了save方法,没有findAll方法,测试代码里的Idea是未定义变量,属于手误,需要替换为你实际的User模型逻辑。
- 修正测试逻辑错误
修正后测试代码示例
"use strict"; const chai = require('chai'); const {match, stub, resetHistory, spy} = require('sinon'); const proxyquire = require('proxyquire'); var sinonChai = require("sinon-chai"); chai.should(); chai.use(sinonChai); const {makeMockModels} = require('sequelize-test-helpers'); describe('User Service', function () { const uid = '6a88e9b5-33a2-403f-ac3d-e86413ac101d' const mockUserData = { email: 'testface@test.com', password: '123456', is_admin: false, first_name: 'Testy', last_name: 'McTestface', google_id: null, facebook_id: null } describe('save()', function () { it('should update existing user when uid exists', async function () { const updateStub = stub().resolves(mockUserData); const User = { findOne: stub().resolves({ update: updateStub }) }; const mockModels = makeMockModels({User}); // 路径和覆写key都严格匹配业务代码 const save = proxyquire('../../services/userService.js', { "../models": mockModels }); const result = await save({ id: uid, email: 'new@test.com' }); User.findOne.should.have.been.calledWith({ where: { uid } }); updateStub.should.have.been.calledWith({ email: 'new@test.com' }); result.should.deep.equal(mockUserData); }); }) });
内容的提问来源于stack exchange,提问作者Mohamed
相关产品推荐
相关产品推荐

