I created a simple jQuery plugin, which modifies the HTML according to some simple rules, using jQuery. Now I need to test that it works. I use Gulp for build automation. I decided to use Jasmine for unit testing. My question is how do I run my plugin from the test.js and validate the result? I have node.js installed at the build server.
Solution
Use jsdom to emulate a browser within your Jasmine unit tests.
Details
jsdom is "a pure-JavaScript implementation of many web standards...for use with Node.js...to emulate enough of a subset of a web browser to be useful for testing and scraping real-world web applications".
jsdom has become the de facto standard for emulating a browser within Node.js. It has over 2 million weekly npm downloads and, among other things, is included automatically as the default test environment in Jest.
jsdom provides the window needed to initialize jQuery, load a jQuery plugin, and unit test it using Jasmine from within Node.js as if it were running in a browser:
colorize-spec.js
const { JSDOM } = require('jsdom');
const { window } = new JSDOM();
global.$ = require('jquery')(window);
require('../src/colorize');
describe('colorize', () => {
const div = $('<div/>');
const settings = { 30: 'highest', 20: 'middle', 10: 'lowest' };
it('should set the applicable class', () => {
div.text('35').colorize(settings);
expect(div.attr('class')).toBe('highest');
div.text('25').colorize(settings);
expect(div.attr('class')).toBe('middle');
div.text('15').colorize(settings);
expect(div.attr('class')).toBe('lowest');
div.text('5').colorize(settings);
expect(div.attr('class')).toBe('');
});
});
I created a pull request that includes jsdom as a dev dependency, bumps node to v8 in Travis CI, and includes this initial unit test. It passes the build checks (including this unit test) and is ready to merge.
Your best bet is to use the gulp-jasmine-browser npm plugin. This will allow you to run your tests in a normal browser, or headless browser. The gulp task you need to create is something like this:
let gulp = require('gulp');
let jasmineBrowser = require('gulp-jasmine-browser');
gulp.task('jasmine', () => {
return gulp.src(['src/**/*.js', 'spec/**/*_spec.js'])
.pipe(jasmineBrowser.specRunner())
.pipe(jasmineBrowser.server({port: 8888}));
});
Or, if you want to run in a headless server, change the last line to this:
.pipe(jasmineBrowser.headless({driver: 'chrome'}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With