假设我有一些需要 jQuery 的测试。好吧,我们不必相信,我确实有测试。测试本身并不重要,但它们依赖于 jQuery 的事实很重要。
Disclaimer: this is node.js so you cannot depend on global variables in your solution. Any dependency must be called into the file with
require
.
在服务器上我们需要这个API(来模拟服务器端jquery所需的窗口对象)
// somefile.js
var jsdom = require("jsdom").jsdom;
var window = jsdom().parentWindow();
var $ = require("jquery")(window);
// my tests that depend on $
// ...
在客户端我们需要一个稍微不同的 API
// somefile.js
// jsdom is not required obviously
// window is not needed because we don't have to pass it to jquery explicitly
// assume `require` is available
// requiring jquery is different
var $ = require("jquery");
// my tests that depend on $
// ...
<小时/>
这是一个大问题!
每个环境的设置都不同,但是重复每个测试只是为了更改设置是完全愚蠢的。
我觉得我忽略了一些简单的事情。
<小时/>如何编写需要 jQuery
的单个测试文件并在多个环境中运行它?
- 在终端中通过
npm test
- 在浏览器中
其他信息
这些信息对于解决这里的根本问题来说并不是必需的;通用解决方案是可以接受的。但是,我正在使用的工具可能具有可以更轻松地解决此问题的组件。
- 我使用
mocha
进行测试 - 我正在使用
webpack
- 我没有和
jsdom
结婚,如果有更好的东西,我们就用它吧! - 我还没有使用过
phantomjs
,但如果它能让我的生活更轻松,那就使用吧!
其他想法:
- 这是 jQuery 的错吗,因为它没有遵守实际的 UMD ?为什么会根据环境需要提供不同的 API?
最佳答案
我正在使用karma直接从命令行运行我的单元测试(CI也是如此,使用 gulp )。
Karma 使用 phantomjs要在 headless 浏览器中运行测试,您也可以将其配置为在真实浏览器中运行。
gulp 内部 karma 配置示例:
// Run karma tests
gulp.task("unit", function (done) {
var parseConfig = require("karma/lib/config").parseConfig,
server = karma.server,
karmaConfig = path.resolve("karma.conf.js"),
config = parseConfig(karmaConfig, {
singleRun: true,
client: {
specRegexp: ".spec.js$"
}
});
server.start(config, done);
});
就我的测试而言,大约需要花费时间。 10秒运行750个测试,速度相当快。
关于javascript - 如何在多个环境(终端和浏览器)中运行JavaScript测试脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26334873/