Mocha测试调用CommonJS导出方法时报validate不是函数如何解决
问题原因
- customer.js导出的是一个接收实例对象作为入参、为入参对象挂载validate方法的函数,而非直接导出带有validate方法的实例对象
- 测试代码中require得到的instance本质是上述导出的函数,本身没有validate属性,因此调用时抛出类型错误
解决方案
方案1:保留现有customer.js的导出逻辑,修改测试文件代码
调整测试代码逻辑,先声明空对象传入导出的工厂函数,挂载完validate方法后再调用,同时注意async异步方法的正确处理:
// 引入的customerExport是导出的工厂函数 const customerExport = require("../customer") // 声明空实例对象 const instance = {} // 调用工厂函数为实例挂载validate方法 customerExport(instance) /* eslint-disable no-undef */ describe('customer', () => { describe('/POST customers', () => { // 异步用例改用async/await写法更稳妥 it('Create Buy customer', async () => { await instance.validate({}) }); }) });
如果要保留done写法,需要捕获异步异常:
it('Create Buy customer', (done) => { instance.validate({}) .then(() => done()) .catch(err => done(err)) });
方案2:修改customer.js的导出逻辑,直接导出带validate的实例
如果你的业务场景不需要接收外部传入的instance对象,可以直接调整导出内容:
const instance = {} instance.validate = async (ctx) => { // some code here } module.exports = instance
修改后测试代码不需要调整即可正常运行。
补充说明:如果调整代码后出现模块找不到的报错,确认你是在server根目录下执行
mocha test/customer.test.ts即可。
内容的提问来源于stack exchange,提问作者sheetaldharerao
相关产品推荐
相关产品推荐

