如何测试这个非常古老的遗留 Javascript 模块而不重写它?
如何加载并实例化这个旧版 javascript 模块以进行测试而不对其进行修改?
遗留模块 (foo.js
):
var Smurf = {};
Smurf.Foo = function() {};
Smurf.Foo.prototype = {
bar: function() {
return 'baz';
}
};
遗留前端(工作):
<script src="foo.js"></script>
<script type="text/javascript">
$(function(){
var foo = new Smurf.Foo();
var qux = foo.bar();
});
</script>
新测试(失败):
const something = require('foo.js');
var foo = new Smurf.Foo();
结果:
Error: Failed to load file test/test.js
ReferenceError: Smurf is not defined
How do I load and instantiate this legacy javascript module for testing, without modifying it?
The legacy module (foo.js
):
var Smurf = {};
Smurf.Foo = function() {};
Smurf.Foo.prototype = {
bar: function() {
return 'baz';
}
};
The legacy front-end (working):
<script src="foo.js"></script>
<script type="text/javascript">
$(function(){
var foo = new Smurf.Foo();
var qux = foo.bar();
});
</script>
The new test (failing):
const something = require('foo.js');
var foo = new Smurf.Foo();
Result:
Error: Failed to load file test/test.js
ReferenceError: Smurf is not defined
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 NodeJS 中,您可以使用
vm
模块 https:// nodejs.org/api/vm.html#vmruninthiscontextcode-options。In NodeJS, you can use the
vm
module https://nodejs.org/api/vm.html#vmruninthiscontextcode-options.您可以做的是将需要测试的文件和包含测试的文件都包含在新的 html 文件中。这样,首先加载需要测试的文件,并且可以在测试文件中测试其中的所有内容。
test.hml
:每次需要运行测试时,在浏览器中打开
test.html
。当然,您需要重写测试文件,以便它在控制台或 html 本身中显示一些输出。What you can do is include both the file you need to test and the file with the tests in a new html file. This way, first the file that needs testing is loaded and everything it has in it can be tested in the test file.
test.hml
:Every time you need to run a test, open
test.html
in a browser. Of course you need to rewrite the test file so it shows some output, either in theconsole
or in the html itself.旧版模块不是CommonJS模块,因此require()将不起作用。我建议阅读这篇 帖子 以了解 require( )有效。
简短的答案是 - 你不能“require()”foo.js 并访问 Smurf 除非 foo.js 正在导出它(使用类似 module.exports 的东西)。
既然您提到不想重写遗留代码,我想向您指出这个巧妙的技巧使用客户端 vanilla 在 ES 模块中导入非 ESM 库JS
The legacy module isn't a CommonJS module, therefore require() will not work. I recommend reading through this post to understand how require() works.
The short answer would be - you cannot "require()" foo.js and access Smurf unless the foo.js is exporting it (using something like module.exports).
Since you mentioned not wanting to rewrite the legacy code, I'd like to point you to this neat trick to Import non-ESM libraries in ES Modules, with client-side vanilla JS