使用Mocha测试未导出函数报错‘xx is not a function’求助
解决Mocha测试IIFE封装的私有函数报错问题
你遇到的问题根源在于:isParamValid 是定义在立即执行函数表达式(IIFE)的局部作用域内的,而 rewire 默认只能访问模块顶级作用域的变量,所以直接用 settings.__get__('isParamValid') 会找不到这个函数。
下面给你两种可行的解决方案:
方案一:间接测试私有函数(无需额外工具)
既然不能修改settings.js,你可以通过调用导出的getSettings函数,根据它的行为反向验证isParamValid的逻辑。比如假设isParamValid在参数无效时会抛出错误,测试代码可以这样写:
// settings.test.js const settings = require('./settings.js'); const { expect } = require('chai'); describe('isParamValid (间接测试)', () => { it('should reject invalid params', () => { // 假设isParamValid在参数(1,1)时会抛出错误 expect(() => settings.getSettings(1, 1)).to.throw('Invalid params'); }); it('should accept valid params', () => { expect(() => settings.getSettings(0, 1)).not.to.throw(); expect(() => settings.getSettings(1, 0)).not.to.throw(); }); });
这种方法不需要修改原代码,也不用额外工具,缺点是无法直接测试isParamValid的返回值,只能通过它对getSettings的影响来验证。
方案二:使用babel-plugin-rewire直接获取私有函数
如果一定要直接测试isParamValid的逻辑,可以借助babel-plugin-rewire,它能深入函数作用域提取私有变量。步骤如下:
- 安装依赖:
npm install --save-dev babel-plugin-rewire @babel/core @babel/register
- 在项目根目录创建
.babelrc配置文件:
{ "plugins": ["rewire"] }
- 修改测试代码,使用
rewire的专属API(注意此时用法和原生rewire略有不同):
// settings.test.js const settings = require('./settings.js'); const { expect } = require('chai'); describe('isParamValid (直接测试)', () => { it('should validate param correctly', () => { // 通过__GetDependency__获取IIFE内部的isParamValid函数 const isParamValid = settings.__GetDependency__('isParamValid'); expect(isParamValid(0, 1)).to.equal(true); expect(isParamValid(1, 0)).to.equal(true); expect(isParamValid(1, 1)).to.equal(false); }); });
- 运行测试时需要用babel-register转译:
mocha --require @babel/register settings.test.js
这种方法可以直接测试私有函数的逻辑,但需要引入Babel相关工具,适合对测试粒度要求较高的场景。
内容的提问来源于stack exchange,提问作者jamu
相关产品推荐
相关产品推荐

