我有一个用 ES6 之前的 JS 代码编写的纯 JS 文件,我想使用 karma/jasmine 测试套件进行测试。该文件很大,但我只想让一个超级简单的示例正常工作。
// pluginV3.js
// This is the file I am trying to test. It is written in pre ES6 JS and has no exports
var myvar = null;
我找到了一个名为rewire的库,我认为它可以让我测试像这样的普通 JS 文件,但我无法让它与我的 karma/jasmine 堆栈一起工作。到目前为止,我已经尝试过:
// var rewire = require("rewire"); // Can't use require. Test code is also pre ES6
beforeEach(module('rewire')); // I have been trying to instance "rewire" here using the exported module in rewire's index.js
describe('V3 Helper.js', function() {
describe('$pluginV3.myvar', function () {
fit('Tests a certain variable in pluginV3 is set to an expected initial value', function () {
var pluginV3 = rewire("../../../../public/static/js2/pluginV3.js");
expect(pluginV3.myvar).toEqual(null); // expect this scope var to be something
});
});
});
但我得到这个错误:
LOG: '----------------------------------------------------'
Chrome 96.0.4664.55 (Mac OS 10.15.7): Executed 0 of 30 SUCCESS (0 secs / 0 secs)
LOG: 'What is rewire?'
Chrome 96.0.4664.55 (Mac OS 10.15.7): Executed 0 of 30 SUCCESS (0 secs / 0 secs)
LOG: function rewire(filename) { ... }
Chrome 96.0.4664.55 (Mac OS 10.15.7): Executed 0 of 30 SUCCESS (0 secs / 0 secs)
Chrome 96.0.4664.55 (Mac OS 10.15.7) CN Plugin Client V3 Helper $scope.transferData Tests a certain variable in Plugin Client V3 is set to an expected initial value FAILED
TypeError: rewireModule is not a function
at rewire (node_modules/rewire/lib/index.js:11:12)
at UserContext.<anonymous> (tests/helpers/cn-plugin-client-v3-test.js:25:28)
at <Jasmine>
Chrome 96.0.4664.55 (Mac OS 10.15.7): Executed 1 of 30 (1 FAILED) (0 secs / 0.002 secs)
Chrome 96.0.4664.55 (Mac OS 10.15.7) CN Plugin Client V3 Helper $scope.transferData Tests a certain variable in Plugin Client V3 is set to an expected initial value FAILED
TypeError: rewireModule is not a function
at rewire (node_modules/rewire/lib/index.js:11:12)
at UserContext.<anonymous> (tests/helpers/cn-plugin-client-v3-test.js:25:28)
at <Jasmine>
这让我觉得它beforeEach(module('rewire'));
正在工作,但由于某种原因它无法运行 rewireModule(也许是因为它是 ES6+)?这是 rewire 的 index.js:
var rewireModule = require("./rewire.js");
/**
* Adds a special setter and getter to the module located at filename. After the module has been rewired, you can
* call myModule.__set__(name, value) and myModule.__get__(name) to manipulate private variables.
*
* @param {!String} filename Path to the module that shall be rewired. Use it exactly like require().
* @return {*} the rewired module
*/
function rewire(filename) {
return rewireModule(module.parent, filename);
}
module.exports = rewire;
delete require.cache[__filename]; // deleting self from module cache so the parent module is always up to date
这是我在我的 karmaconfig 文件中导入的内容以及我要测试的文件:
// karma.conf.js
files: [
'./node_modules/rewire/lib/index.js',
'../../public/static/js2/cn-plugin-client-v3.js',
]
难道我做错了什么?或者我只是无法在 ES6 之前的限制下使用 rewire。有没有人用 karma/jasmine 测试过没有导出的 pre ES6 JS 文件?有不同的解决方案吗?