- Регистрация
- 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?
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
// sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
// sum.test.js
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
{
"scripts": {
"test": "jest"
}
}
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: .
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.
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
- 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;
- 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);
});
- Configure Test Script: Add the following script to your package.json:
{
"scripts": {
"test": "jest"
}
}
- 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: .