In this tutorial, we aim to introduce you to the fundamentals of unit testing. You will learn how to write and run unit tests for your HTML and JavaScript code, using popular testing frameworks.
Basic knowledge of HTML and JavaScript is required.
Unit testing is a type of testing where individual parts of your code are tested to ensure that they work as expected. These 'units' can be functions, method, interfaces, or classes.
Unit testing ensures that your code works correctly, helps in identifying and fixing bugs early, and makes refactoring code easier. It also provides documentation of the system.
Unit tests are written in such a way that they are small, independent, and test only one thing. Here is a basic structure of a unit test:
We will use a simple JavaScript function that adds two numbers and write a test for it using the Jest testing framework.
// function to test
function add(a, b) {
return a + b;
}
// test
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
add
which adds two numbers.test
function is provided by Jest and it takes two arguments: a string description of the test and a callback function for the test code.expect
and toBe
to assert that the add
function returns the correct value.PASS ./add.test.js
✓ adds 1 + 2 to equal 3 (5 ms)
The test passed, which means our function works as expected.
In this tutorial, you have learned the basics of unit testing, how to write and run them using a testing framework. You've also practiced writing a unit test for a simple JavaScript function.
Now, you can move on to testing more complex functions or even classes. You can also learn about different types of testing, like integration testing and end-to-end testing.
// function to test
function factorial(n) {
return (n != 1) ? n * factorial(n - 1) : 1;
}
// test
test('factorial of 5 is 120', () => {
expect(factorial(5)).toBe(120);
});
// function to test
function sortArray(arr) {
return arr.sort((a, b) => a - b);
}
// test
test('sorts array in ascending order', () => {
expect(sortArray([5, 3, 4, 1, 2])).toEqual([1, 2, 3, 4, 5]);
});
Keep practicing and exploring more about JavaScript unit testing. Happy coding!