JavaScript Testing: Jasmine plugins

JavaScript Testing: Jasmine plugins

posted in javascript on • last updated 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

thlorenz/proxyquire : Proxies nodejs require in order to allow overriding dependencies during testing.


and some custom reporters:

bcaudan/jasmine-spec-reporter : Real time console spec reporter for jasmine testing framework

Marak/colors.js : Color configuration for jasmine-spec-reporter

larrymyers/jasmine-reporters : Reporter classes for the jasmine test framework.


Other Jasmine plugins you might find useful:

node-nock/nock : HTTP server mocking and expectations library for Node.js

visionmedia/supertest : Super-agent driven library for testing node.js HTTP servers using a fluent API.

jhnns/rewire : Use rewire('./file.js') instead of require() and get a fresh copy each time

Reporters

Jasmine Spec Reporter

Probably your goto console logger: jasmine-spec-reporter:

npm install jasmine-spec-reporter --save-dev

Usage:

const SpecReporter = require('jasmine-spec-reporter').SpecReporter;

jasmine.getEnv().clearReporters();
jasmine.getEnv().addReporter(new SpecReporter({
  spec: {
    displayPending: true,
    // See configuration.d.ts for more config
    // Colors: https://github.com/Marak/colors.js
    colors: {
        failed: 'magenta',
        prettyStacktraceError: 'magenta',
    }
  }
}));

Jasmine-Reporters

A collection of reporters: JUnitXmlReporter, NUnitXmlReporter, AppVeyor, TapReporter, TeamCityReporter and TerminalReporter.

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);
  });
});

VSCode Integration

The Jest VSCode test runner got me thinking, this probably also exists for Jasmine.

hbenl/vscode-jasmine-test-adapter : Jasmine Test Adapter for the VS Code Test Explorer

And instructions for setting up a launch.json on Stackoverflow


Stuff that came into being during the making of this post
Updates
  • 28 March 2023 : Colorblindness: added color configuration + added jasmine-reporters
  • 17 January 2019 : Added reporter plugins
Tags: tutorial testing