JavaScript Testing: Jasmine plugins

JavaScript Testing: Jasmine plugins

posted in javascript on

What would we be without some extra plugins. There are over 1000 Jasmine npm packages and we’ll cover them all here.

Or apparently just proxyquire ;)

Other Jasmine plugins that you might find useful:

  • nock: Test Http requests
  • rewire: Use rewire('./file.js') instead of require() and get a fresh copy each time

Proxyquire

Stub imports of the code being tested.

npm install --save-dev proxyquire

api.js:

module.exports = {
  someLongRunningOperation: function() {
    for (var i = 0; i <= 1000; i++) {}
  }
};

cut.js:

const webApi = require('./api.js');
module.exports = function() {
  webApi.someLongRunningOperation();
};

spec.js:

const proxyquire = require('proxyquire');
var apiStub = {};
const cut = proxyquire('./cut.js', {'./api.js': apiStub});

describe('fake the api call', function() {
  beforeEach(function() {
    this.hasRunStub = false;
    apiStub.someLongRunningOperation = () => this.hasRunStub = true;
  });

  it('should not actually call the api', function() {
    cut();
    expect(this.hasRunStub).toBe(true);
  });
});

Stuff that came into being during the making of this post