在开玩笑测试中加载Jest和Bower模块

让我们说我有一个项目,使用凉亭,咕噜,bowerify(与垫片),因为我非常喜欢开玩笑,我想测试它.在运行测试时,如何在世界上看到我的浏览器垫片模块.我使用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所以将浏览器的所有内容与我的设置相结合,我可以要求我这样的shimmed模块.
require(‘jquery’)//示例但是在jest cli中测试失败,因为他们可以找到模块,除非我以某种方式用./加前缀,如此需要(‘./ jquery’)

最佳答案 我猜你的问题是你只用凉亭安装了你的shimmed模块.如果你想让它们在node / jest中工作,你也必须用npm安装它们.然后确保Jest没有在node_modules目录中模拟任何东西,只要名称匹配,它就应该在那里找到所有必需的模块.

你在package.json中的Jest配置应如下所示:

"jest": {
  "unmockedModulePathPatterns": [
    "./node_modules"
  ]
}

然后只需下载所有依赖项.

npm install jquery --save-dev
点赞