假设我有一个使用 bower、grunt、bowerify(使用 shim)的项目,因为我非常喜欢 Jest,所以我想用它来测试。当我运行测试时,我怎么会开玩笑地看到我的 browserify shim 模块。我使用 grunt 来启动 npm test 命令。这是我的 package.json 文件。
"browser": {
"jquery": "./bower_components/jquery/dist/jquery.js",
"foundation": "./bower_components/foundation/js/foundation/foundation.js",
"fastclick": "./bower_components/fastclick/lib/fastclick.js",
"greensock-tm": "./bower_components/gsap/src/uncompressed/TweenMax.js",
"greensock-css": "./bower_components/gsap/src/uncompressed/plugins/CSSPlugin.js",
"greensock-time": "./bower_components/gsap/src/uncompressed/TimelineMax.js",
"scrollmagic": "./bower_components/ScrollMagic/js/jquery.scrollmagic.js",
"handlebars": "./bower_components/handlebars/handlebars.runtime.js"
},
"browserify-shim": {
"jquery": "$",
"greensock-css": "CSSPlugin",
"fastclick": "FastClick",
"greensock-tm": "TweenMax",
"greensock-time": "TimelineMax",
"scrollmagic": "ScrollMagic",
"foundation": "foundation",
"handlebars": "Handlebars"
},
"browserify": {
"transform": [
"browserify-shim"
]
},
现在,在运行测试之前,我几乎可以通过在我的 grunt 文件中执行此操作来解决此问题。
grunt.registerTask("shimBowerForTests",function(){
var readJson = require('read-package-json');
var fs = require('fs');
var remapify = require('remapify');
readJson('./package.json', console.error, false, function (er, data) {
if (er) {
throw "There was an error reading the file";
}
var packages = data.browser;
var browserify = require('browserify');
for (var key in packages){
var b = browserify();
var wstream = fs.createWriteStream("devjs/test/modules/"+key+'.js');
b.add(packages[key]);
b.bundle().pipe(wstream);
}
});
});
和。
exec: {
jestTest: {
command: 'cp -r devjs/modules devjs/test/modules && npm test'
}
}
问题是使用browserify,所以将浏览器的所有内容与我的设置结合起来效果很好,我可以像这样要求我的垫片模块。
require('jquery') //example
但是在开玩笑的cli中,测试失败了,因为他们可以找到模块,除非我以某种方式在它前面加上./,就像这样require('./jquery')