Loading...

Go Back

Next page
Go Back Course Outline

JavaScript Full Course


Testing JavaScript Code

Testing JavaScript Code

1. Introduction to Testing

Testing is a critical part of the development process. It ensures that your code works as expected, is reliable, and reduces the chances of bugs appearing in production. There are two major types of tests:

  • Unit Testing: Tests individual units of code (usually functions or methods).
  • Integration Testing: Ensures that multiple parts of the application work together as expected.


2. Testing Frameworks

Jest is a popular testing framework, especially for React applications. It includes a test runner and assertion library.

Mocha is another popular framework often used with Node.js and allows you to use different assertion libraries like Chai.

3. Writing Test Cases

Here’s an example of how to write test cases using Jest. Let’s say you have a simple function `add` that adds two numbers together:

Example: Testing an Add Function Using Jest

                        
                        // add.js
                        function add(a, b) {
                          return a + b;
                        }
                        
                        module.exports = add;
                        
                        // add.test.js
                        const add = require('./add');
                        
                        test('adds 1 + 2 to equal 3', () => {
                          expect(add(1, 2)).toBe(3);
                        });
                        
                        test('adds -1 + 2 to equal 1', () => {
                          expect(add(-1, 2)).toBe(1);
                        });
                        
                            


4. Test-Driven Development (TDD)

TDD is an approach where you write tests before the code, following the "Red-Green-Refactor" cycle.

Example of TDD with Multiply Function

                        
                        // multiply.test.js
                        const multiply = require('./multiply');
                        
                        test('multiplies 2 and 3 to equal 6', () => {
                          expect(multiply(2, 3)).toBe(6);
                        });
                        
                        // multiply.js
                        function multiply(a, b) {
                          return a * b;
                        }
                        
                        module.exports = multiply;
                        
                            

5. Running Tests

After writing your tests, you can run them using Jest. To do so, run the following command:

                        
                        npx jest
                        
                            

6. Output

Go Back

Next page