Unit testing is a crucial aspect of software development that ensures individual parts of your code work as expected. For jQuery, this involves writing tests that verify the correctness of your jQuery functions, plugins, and interactions with the DOM. Test automation further enhances this process by allowing you to run tests automatically, ensuring that your code remains reliable and bug-free as it evolves.In this chapter, we'll cover everything you need to know about unit testing and test automation for jQuery, from basic concepts to advanced techniques, with detailed examples and explanations.
Unit testing involves testing individual units or components of a software application. The purpose is to validate that each unit performs as expected.
You can include QUnit via a CDN or install it using npm.
npm install --save-dev qunit
A QUnit test consists of modules, test cases, and assertions.
QUnit.module('Basic Module');
QUnit.test('Simple Test', function(assert) {
assert.ok(true, 'This test will always pass.');
assert.equal(1 + 1, 2, '1 + 1 should equal 2');
});
To test jQuery selectors and DOM manipulations, you need to set up your HTML fixture and write tests that interact with the DOM.
Hello World
QUnit.module('jQuery Selectors');
QUnit.test('Selects element by class', function(assert) {
var element = $('.test-element');
assert.ok(element.length > 0, 'Element with class "test-element" exists.');
assert.equal(element.text(), 'Hello World', 'Element text is "Hello World".');
});
Event handlers are a common feature in jQuery applications. Testing these requires simulating events and verifying the resulting behavior.
QUnit.module('jQuery Events');
QUnit.test('Button click event', function(assert) {
var done = assert.async();
$('#test-button').on('click', function() {
assert.ok(true, 'Button was clicked.');
done();
});
$('#test-button').trigger('click');
});
done
is called.Testing AJAX calls involves mocking the requests to avoid making real HTTP requests during testing.
QUnit.module('jQuery AJAX');
QUnit.test('AJAX request', function(assert) {
var done = assert.async();
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1',
method: 'GET',
success: function(data) {
assert.ok(data, 'AJAX call succeeded.');
assert.equal(data.id, 1, 'Returned data has correct ID.');
done();
},
error: function() {
assert.ok(false, 'AJAX call failed.');
done();
}
});
});
To avoid making real HTTP requests in tests, you can use libraries like Sinon.js to mock AJAX calls.
QUnit.module('Mocking AJAX Calls', {
beforeEach: function() {
this.server = sinon.createFakeServer();
},
afterEach: function() {
this.server.restore();
}
});
QUnit.test('Mocked AJAX request', function(assert) {
var done = assert.async();
this.server.respondWith('GET', '/api/data', [
200,
{ 'Content-Type': 'application/json' },
JSON.stringify({ id: 1, name: 'Test' })
]);
$.ajax({
url: '/api/data',
method: 'GET',
success: function(data) {
assert.ok(data, 'Mocked AJAX call succeeded.');
assert.equal(data.id, 1, 'Returned data has correct ID.');
done();
}
});
this.server.respond();
});
/api/data
with a 200 status and a JSON response./api/data
.Grunt is a JavaScript task runner that can automate running your QUnit tests.
npm install grunt --save-dev
npm install grunt-contrib-qunit --save-dev
module.exports = function(grunt) {
grunt.initConfig({
qunit: {
files: ['index.html']
}
});
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.registerTask('default', ['qunit']);
};
grunt
index.html
.GitHub Actions can automate running your QUnit tests as part of your CI/CD pipeline.
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14, 16, 18]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npx qunit
Unit testing and test automation are powerful tools in a developer’s arsenal. While it may seem daunting at first, the benefits far outweigh the initial effort required to set up and write tests. As you continue to develop and maintain jQuery applications, the skills and knowledge gained from this chapter will serve as a valuable resource, helping you to create reliable and high-quality code.Happy coding !❤️