简体   繁体   English

测试互斥 JavaScript

[英]Testing mutually exclusive JavaScript

I'm working on a web application that includes different JavaScript files, depending on where I am in the app.我正在开发一个 web 应用程序,其中包括不同的 JavaScript 文件,具体取决于我在应用程序中的位置。 For instance, I have a display.js for each page, each of which has an "init()" function that is called as soon as the page is loaded.例如,我对每个页面都有一个 display.js,每个页面都有一个“init()”function,它会在页面加载后立即调用。

This works well for the webapp, but in my QUnit tests, where all script files are included from a single index.html, functions of the same names override each other.这适用于 webapp,但在我的 QUnit 测试中,所有脚本文件都包含在单个 index.html 中,相同名称的函数相互覆盖。

How are such problems best handled?如何最好地处理这些问题? One test index.html file per page creates lots of boilerplate code and makes it non-trivial to execute all test cases.一个测试索引。html 文件每页创建大量样板代码,并使得执行所有测试用例变得不平凡。 That's why I decided to name each and every function distinctively, eg "initFrontPage()" instead of "init()".这就是为什么我决定给每一个 function 分别命名,例如“initFrontPage()”而不是“init()”。 This, however, makes the application code a bit weird: Not only do I have to include the right file, I also have to call the right functions in it.然而,这使得应用程序代码有点奇怪:我不仅必须包含正确的文件,还必须在其中调用正确的函数。 Is there a better way?有没有更好的办法?

The solution is to use namespaces:解决方案是使用命名空间:

In foo/display.js:在 foo/display.js 中:

window.foo = {};
foo.init = function () { ... };

In bar/display.js:在 bar/display.js 中:

window.bar = {};
bar.init = function () { ... };

Then, in the page that uses bar/display.js's init method:然后,在使用 bar/display.js 的init方法的页面中:

(function (display) {
    display.init();
}(bar));

It would be a good idea to wrap your display.js code in an IIFE as well.将 display.js 代码包装在IIFE中也是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM