Browserify/Rewireify unit testing, how to inject dependencies without a bundle?

时光怂恿深爱的人放手 提交于 2019-12-11 09:56:14

问题


Browserify handles dependencies nicely by requiring them and creating a bundle where all is in order. When unit testing a module that has it's own dependencies it's somewhat more complicated though.

My tests are using mocha, sinon, chai.

My app is built on backbone, marionette, and some jQuery plugins.

I'm putting it together with grunt and browserify, all is written in coffeescript.

For instance, I have a module looking like this:

# Global, because swosh won't know what jQuery is otherwise.
$ = global.jQuery = require 'jquery'
require '../jqueryPlugins/swosh.js'

module.exports =
  App.MyView: Mn.ItemView.extend
    # Here I make use of jQuery plugin swosh

When I'm testing this piece of code, I'll do it like this:

App = require '../src/swoshViews.coffee'

theView = new App.MyView
describe 'Swooshing'
  it 'swooshes', ->
    # I create a spy/stub of the jQuery plugin
    # and make sure it's called as expected.

Since Browserify isn't a dependency injection framework, the jQuery plugin will not be available for the module, there are some options to make that happen. The most suitable for me seems to be Rewireify.

I'm running my tasks with Grunt, where browserify is run win the transformations ['coffeeify', 'rewireify']. However, and here's my question:

My unit tests, being run with npm test, doesn't use a browser.

package.json extract:

"scripts": {
  "test": "mocha"
},

Grunt>Browserify will arrange a .js bundle for me with rewireify baked in, though how do I apply this for my npm test task? My npm test script simply runs mocha, as seen above, which will run tests in all my unit test files, no need for a bundle. How do I make use of rewireify this way?

来源:https://stackoverflow.com/questions/33516371/browserify-rewireify-unit-testing-how-to-inject-dependencies-without-a-bundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!