• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Unit Testing with Jest

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Jest is a delightful JavaScript testing framework developed by Meta (formerly Facebook). It offers a zero-configuration setup, making it an excellent choice for developers looking to implement unit tests efficiently.

Why Choose Jest?

  • Zero Configuration: Jest works out of the box for most JavaScript projects.
  • Fast and Safe: Runs tests in parallel processes, ensuring speed and isolation.
  • Snapshot Testing: Easily track changes in large objects over time.
  • Rich API: Provides a comprehensive set of matchers and utilities.
Getting Started

Installation


To install Jest in your project, use your preferred package manager:


npm install --save-dev jest
# or
yarn add --dev jest
Writing Your First Test

  1. Create a Function to Test: Let's write a simple function that adds two numbers.

// sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
  1. Write the Test Case: Create a test file named sum.test.js.

// sum.test.js
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
  1. Configure Test Script: Add the following script to your package.json:

{
"scripts": {
"test": "jest"
}
}
  1. Run the Test: Execute the test using:

npm test
# or
yarn test

You should see an output indicating the test has passed.

Testing Asynchronous Code


Jest handles asynchronous code gracefully. Here's how you can test asynchronous functions:


// asyncFunction.js
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve('peanut butter');
}, 100);
});
}
module.exports = fetchData;

// asyncFunction.test.js
const fetchData = require('./asyncFunction');

test('the data is peanut butter', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
});
Snapshot Testing


Snapshot testing is useful for ensuring UI components don't change unexpectedly.


// component.js
function createComponent() {
return {
title: 'Test Component',
content: 'This is a test.'
};
}
module.exports = createComponent;

// component.test.js
const createComponent = require('./component');

test('component matches the snapshot', () => {
const component = createComponent();
expect(component).toMatchSnapshot();
});

Running this test will create a snapshot file. Future runs will compare the output to this snapshot.

Mock Functions


Jest allows you to mock functions to isolate the code under test.


// user.js
function getUser(callback) {
callback('John Doe');
}
module.exports = getUser;

// user.test.js
const getUser = require('./user');

test('calls the callback with "John Doe"', () => {
const mockCallback = jest.fn();
getUser(mockCallback);
expect(mockCallback).toHaveBeenCalledWith('John Doe');
});
Conclusion


Jest provides a robust and user-friendly platform for unit testing in JavaScript. Its features like zero configuration, snapshot testing, and easy mocking make it a go-to choice for developers aiming to maintain high code quality.

For more detailed information and advanced configurations, refer to the official Jest documentation:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу