Skip to content

Instantly share code, notes, and snippets.

@rrgayhart
Last active June 26, 2022 06:09
Show Gist options
  • Save rrgayhart/cf5dcefdf3975598f491 to your computer and use it in GitHub Desktop.
Save rrgayhart/cf5dcefdf3975598f491 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');

  • 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 --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?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.

    • Replace the var sinon = require('sinon'); with var sinon = require('sinon/pkg/sinon'); in your tests
  • You can find the source of this solution and learn more about the problem in this webpack issue thread

@colinrobertbrooks
Copy link

This did the trick. A couple updates, though:

  • Install imports-loader, not imports:
    • npm install imports-loader --save-dev
  • You can do import sinon from 'sinon' by adding the following to webpack.config.js:
    • resolve: { alias: { sinon: 'sinon/pkg/sinon.js' } }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment