Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a11smiles/2f3371b1f16696cad1685c284b281c82 to your computer and use it in GitHub Desktop.
Save a11smiles/2f3371b1f16696cad1685c284b281c82 to your computer and use it in GitHub Desktop.
Adding Sinon to WebPack

Adding Sinon to WebPack

  • Open your project (if you're using WebPack, obviously)

  • npm install sinon --save-dev

  • You should now have Sinon in your node modules and listed in your package.json file

  • In your tests, require Sinon: var sinon = require('sinon'); or import * as sinon from 'sinon';

  • You should see a strange error in your console, when you open your testing file. If you google that error and the words 'sinon' and 'webpack' you should see a number of Github issues.

    • Evidently, WebPack and Sinonjs have not been playing nicely for some time
    • Sinon doesn't export itself correctly when webpacked - or at least, so says the github issue commenters
    • We can fix it, we have the technology
  • First, if you don't have it already, you'll need to install imports-loader

    • npm install imports-loader --save-dev
  • Now open your webpack.config.js file and look for the module: section. It should look something like this:

  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
      { test: /\.css$/, loader: "style!css" },
      { test: /\.scss$/, loader: "style!css!sass" }
    ]
  },
  • Because of the afor mentioned loading issues, you will have to specifically tell webpack how to import sinonjs. Add the following line to the loaders block:

    • { test: /sinon\.js$/, loader: "imports-loader?define=>false,require=>false"}
  • Now that we are loading Sinon manually, we have to specify in our tests that we should use the built package. In your webpack.config.js add the following property (or update your resolve property):

resolve: { alias: { sinon: 'sinon/pkg/sinon.js' } }
  • You can find the source of this solution and learn more about the problem in this webpack issue thread
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment