0% found this document useful (0 votes)
108 views13 pages

Introduction to Jest Testing Framework

F

Uploaded by

Code Geeks
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views13 pages

Introduction to Jest Testing Framework

F

Uploaded by

Code Geeks
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Testing

What is Testing :

Testing in software development is the process of evaluating and verifying that a software
application or system meets the speci ed requirements. The main objectives are to identify bugs,
ensure the software behaves as expected, and verify that it meets the needs of its users and
stakeholders.

Importance of Testing in Software Development

1. Quality Assurance: Ensures that the software is of high quality by detecting and xing bugs
before the software is released to users.

2. Reliability: Helps ensure the software performs reliably in different scenarios and under
various conditions, minimizing the risk of failures in production.

3. User Satisfaction: Enhances user satisfaction by delivering a product that works as intended
and provides a positive user experience.

4. Cost Ef ciency: Detecting and xing bugs early in the development process is often
cheaper and easier than dealing with issues after the software has been released.

5. Security: Identi es vulnerabilities and potential security issues, helping to prevent data
breaches and other security incidents.

Black Box Testing

Black box testing is a software testing method where the tester evaluates the functionality of the
software without knowing the internal workings or structure of the application. The focus is on
input and output—what the system does, not how it does it.

White Box Testing

White box testing, also known as clear box testing, glass box testing, or structural testing, is a
software testing method in which the internal structure, design, and implementation of the item
being tested are known to the tester. The tester selects inputs to exercise paths through the code and
determines the appropriate outputs.
fi
fi
fi
fi
fi
Types of Testing

1. Unit Testing: Tests individual components or units of code to ensure they work correctly.
2. Integration Testing: Ensures that different modules or services within an application
interact as expected.
3. System Testing: Validates the complete and integrated software to ensure it meets the
speci ed requirements.
4. Acceptance Testing: Veri es the software meets the business requirements and is ready for
delivery.
5. Performance Testing: Assesses how the software performs under various conditions, such
as load, stress, and scalability.
6. Security Testing: Identi es vulnerabilities and ensures the software is secure from attacks.
7. Usability Testing: Evaluates the user interface and user experience to ensure the software is
user-friendly.

Getting Started with Jest

Jest is an open-source testing framework developed by Facebook, primarily designed for testing
JavaScript applications. It is commonly used for testing applications built with frameworks like
React, Angular, and Vue. Jest provides a comprehensive and easy-to-use testing solution that
includes built-in support for various types of testing, including unit, integration, and end-to-end
testing.

Setting Up Jest
Npm install —save-dev jest
Npm install —save-dev superset

First Test

// [Link]
function sum(a, b) {
return a + b;
}

[Link] = sum;
fi
fi
fi
// [Link]
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {


expect(sum(1, 2)).toBe(3);
});

[Link]:

{
"scripts": {
"test": "jest"
}
}

Command to Run: npm test

Core Concepts of Jest


toBe

• Use toBe to test exact equality. This matcher uses [Link] to test for strict equality.
javascript

test('adds 1 + 2 to equal 3', () => {


expect(sum(1, 2)).toBe(3);
});

toEqual

•Use toEqual to test the value of objects. This matcher recursively checks every eld of
an object or array.
test('object assignment', () => {
const data = { one: 1 };
data['two'] = 2;
expect(data).toEqual({ one: 1, two: 2 });
});

toBeNull

• Use toBeNull to match only null.


test('null', () => {
const n = null;
expect(n).toBeNull();
});
fi
toBeDefined

• Use toBeDefined to check if a variable is de ned.

test('defined', () => {
const a = 1;
expect(a).toBeDefined();
});

toBeUndefined

• Use toBeUndefined to check if a variable is undefined.

test('undefined', () => {
let a;
expect(a).toBeUndefined();
});

toBeTruthy

• Use toBeTruthy to match anything that an if statement treats as true.

test('true or false', () => {


const a = true;
expect(a).toBeTruthy();
});

toBeFalsy

• Use toBeFalsy to match anything that an if statement treats as false.


test('false', () => {
const a = 0;
expect(a).toBeFalsy();
});

Testing Functions with Jest


// [Link]
function add(a, b) {
return a + b;
}

function subtract(a, b) {
return a - b;
}

[Link] = { add, subtract };


fi
// [Link]
const { add, subtract } = require('./math');

test('adds 1 + 2 to equal 3', () => {


expect(add(1, 2)).toBe(3);
});

test('subtracts 5 - 3 to equal 2', () => {


expect(subtract(5, 3)).toBe(2);
});

Testing Async Code

// [Link]
function fetchData(callback) {
setTimeout(() => {
callback('admin');
}, 1000);
}

[Link] = fetchData;

// [Link]
const fetchData = require('./sum');

test('the data should be admin', done => {


function callback(data) {
try {
expect(data).toBe('admin');
done();
} catch (error) {
done(error);
}
}

fetchData(callback);
});

Testing with Mocks in Jest

Mocks are useful for isolating the code under test and ensuring that tests are not in uenced by
external dependencies or slow operations. Jest provides powerful tools for mocking functions and
modules, which makes it easier to write unit tests.

To mock functions in Jest, you can use [Link](). This allows you to create mock functions
that you can use to test the interactions within your code.
fl
Mocking Functions

function fetchData(callback) {
setTimeout(() => {
callback('admin');
}, 1000);
}

[Link] = fetchData;

const fetchData = require('./fetchdata');

test('the data should be admin', done => {


function callback(data) {
try {
expect(data).toBe('admin');
done();
} catch (error) {
done(error);
}
}

fetchData(callback);
});

const fetchData2 = require('./fetchdata');

test('calls the callback with apple', done => {


function callback(data) {
try {
expect(data).toBe('apple');
done();
} catch (error) {
done(error);
}
}

fetchData2(callback);
});
test('calls the callback with apple', done => {
const mockCallback = [Link](data => {
expect(data).toBe('apple');
done();
});
fetchData2(mockCallback);
});

Mocking Modules
Jest also allows you to mock entire modules. This is useful when you want to isolate the module
under test from its dependencies.

Mocking Functions: Use [Link]() to create mock functions and test interactions.

Mocking Modules: Use [Link]() to mock entire modules and their functions.

Mock Implementations: You can use mockReturnValue, mockResolvedValue, and


other methods to de ne the behavior of mock functions.

// test/[Link]
function getData() {
return 'real data';
}

[Link] = { getData };

// test/[Link]
const { getData } = require('./utils');

function processData() {
return `Processed: ${getData()}`;
}

[Link] = processData;

// [Link]
[Link]('./test/utils', () => ({
getData: [Link](),
}));

const { getData } = require('./test/utils');


const processData = require('./test/app');

test('processData returns processed data', () => {


fi
[Link]('mocked data');
expect(processData()).toBe('Processed: mocked data');
});

Advanced Jest Features

Jest Setup and Teardown


In Jest, you can use setup and teardown functions to manage test environment setup, initialization,
and cleanup. These functions help ensure that your tests run in a consistent and predictable manner
by setting up common prerequisites before each test (beforeEach) or once before all tests
(beforeAll), and cleaning up after each test (afterEach) or once after all tests
(afterAll).

beforeEach(() => { ... }): Runs before each test case.


afterEach(() => { ... }): Runs after each test case.
beforeAll(() => { ... }): Runs once before all test cases.
afterAll(() => { ... }): Runs once after all test cases.

let initializedData = [];

beforeAll(() => {
// Initialize some data before all tests
initializedData = ['item1', 'item2'];
});

beforeEach(() => {
// Reset or prepare the environment before each test
[Link]('Before each test');
});

afterEach(() => {
// Clean up after each test
[Link]('After each test');
});

afterAll(() => {
// Clean up after all tests
initializedData = [];
});

test('length of initialized data', () => {


expect([Link]).toBe(2);
});

test('example test', () => {


// Access initialized data in another test
expect(initializedData).toContain('item1');
});

JEST on React

React components involves verifying that each component renders correctly, behaves as expected
when interacted with, and correctly updates based on changes to its props or state. Jest and tools
like @testing-library/react or enzyme are commonly used for testing React
components.

npm install --save-dev @testing-library/react

npm install --save-dev @testing-library/jest-dom

// components/[Link]
import React from 'react';

function Button({ onClick, label }) {


return (
<button onClick={onClick} className="btn">
{label}
</button>
);
}

export default Button;

// components/[Link]
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import Button from './button';

test('renders button with label', () => {


const { getByText } = render(<Button label="Click me" />);
const buttonElement = getByText('Click me');
expect(buttonElement).toBeInTheDocument();
});

test('calls onClick prop when button is clicked', () => {


const onClickMock = [Link]();
const { getByText } = render(<Button label="Click me"
onClick={onClickMock} />);
const buttonElement = getByText('Click me');

[Link](buttonElement);

expect(onClickMock).toHaveBeenCalledTimes(1);
});

test('button has correct class', () => {


const { container } = render(<Button label="Click me" />);
const buttonElement = [Link]('button');

expect(buttonElement).toHaveClass('btn');
});

npm test

//working of toHaveBeenCalledTimes();

const mockFunction = [Link]();


// Example test case
test('mock function is called twice', () => {
// Call the mock function twice
mockFunction();
mockFunction();

// Assert that the mock function was called exactly twice


expect(mockFunction).toHaveBeenCalledTimes(2);
});

[Link]() creates a mock function (onClickMock) that replaces the onClick prop of the
Button component.
[Link](buttonElement) simulates a click event on the button.
expect(onClickMock).toHaveBeenCalledTimes(1) veri es that
onClickMock was called exactly once when the button was clicked.
fi
JEST ON SERVER

We will check with jest if mongodb is connected or not before all test

// [Link]
const mongoose = require('mongoose');

describe('MongoDB Connection', () => {

beforeAll(async () => {
const url= ‘your url';

await [Link](url, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
});

test('should connect to MongoDB successfully', () => {


expect([Link]).toBe(1);
});
});

Unit Test on API


//[Link]
async function fetchData() {
try {
const response = await fetch('[Link]
if (![Link]) {
throw new Error('Failed to fetch data');
}
const data = await [Link]();
return data;
} catch (error) {
[Link]('Error fetching data:', error);
throw error; // Propagate the error to the caller
}
}
[Link] = fetchData;
//[Link]
const fetchData = require('./api');
const fetch = require('node-fetch');
[Link]('node-fetch');

test('GET /users should fetch all users', async () => {


const data = await fetchData();

expect(data).toHaveProperty('data');
expect([Link]).toHaveProperty('getAllUsers');

[Link](user => {
expect(user).toHaveProperty('jd');
expect(user).toHaveProperty('email');
expect(user).toHaveProperty('name');
expect(user).toHaveProperty('password');
});
});

Integration testing
Integration testing for server-side code typically involves testing how various components of your
server interact with each other and with external dependencies like databases, APIs, and
middleware. Here’s a general approach to writing integration tests for server-side [Link]
applications using tools like Jest and Supertest

Remove logs and export app in [Link]

[Link] = app; // Export the Express app for testing

Create a [Link] file

const request = require('supertest');


const app = require('./index'); // Adjust the path as per your
project structure

describe('GET /users', () => {


test('it should fetch all users from an API', async () => {
const response = await request(app)
.get('/users')
.expect(200);

expect([Link]).toBeDefined();
const data = [Link];
[Link](data)
expect([Link]([Link])).toBe(false);
[Link](user => {
expect(user).toHaveProperty('id');
expect(user).toHaveProperty('email');
expect(user).toHaveProperty('name');
expect(user).toHaveProperty('password');
});
});
});

Jest in a CI/CD Pipeline


Integrating Jest with a CI/CD pipeline involves setting up automated testing that runs Jest tests
whenever changes are made to your codebase. This ensures that new code additions or updates are
thoroughly tested before deployment.

[Link]

name: Run Jest Tests

on:
push:
branches:
- testing

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v3

- name: Set up [Link]


uses: actions/setup-node@v3
with:
node-version: '16'

- name: Install dependencies


run: npm install

- name: Run Jest tests


run: npm test

You might also like