我正在尝试使用 babel-plugin-rewire 模拟另一个文件中的函数。此函数未导出,但由该文件的默认导出调用。
meteor 1.6.1
"babel-plugin-rewire": "^1.2.0"
meteor 测试:mocha@1.1.2
在我的应用程序的 package.json 中:
"babel": {
"presets": ["latest", "meteor"],
"env": {
"test": {
"plugins": [
"babel-plugin-rewire"
]
}
}
}
在我的 parentFunction.js 中:
import { some function } from 'anotherFile';
function childFunction() {
...
return someValue;
}
export default function parentFunction() {
return childFunction()
}
在我的测试文件中:
import { childFunction, __RewireAPI__ as MyRewireAPI } from './parentFunction'; // eslint-disable-line import/named
if (Meteor.isServer) {
...
describe('parentFunction', () => {
it('uses the mocked child function', () => {
MyRewireAPI.__Rewire__('childFunction', function () {
return Promise.resolve({ 'name': 'bob' });
});
});
});
}
当我使用此命令运行测试时:
TEST_WATCH=1 meteor test --driver-package meteortesting:mocha
我所有的其他测试都通过了,但这个测试失败并出现错误:
TypeError: Cannot read property '__Rewire__' of undefined
我认为 rewire 的意义在于它从文件中获取了一个未导出的模块,那么这是否意味着 rewire 没有运行?我还需要做些什么来将 rewire 插件与 Meteor 的内置 babel 连接起来吗?
我已阅读文档并寻找其他类似问题,但看不出我做错了什么。我将非常感谢关于我在这里缺少什么简单的东西的建议。
编辑:我意识到我没有将 BABEL_ENV 环境变量设置为“测试”,但现在我设置了,但它仍然不起作用。
最佳答案
我今天也试过用 Meteor 重新连接模块,但没有成功。
这可能是一个不错的选择。 像这样有条件地导出被测函数:
import { some function } from 'anotherFile';
function childFunction() {
...
return someValue;
}
export default function parentFunction() {
return childFunction()
}
if (Meteor.isTest || Meteor.isAppTest) {
module.exports = { childFunction };
}
关于javascript - 如何在 Meteor 中启用 babel-plugin-rewire,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55353665/