This content originally appeared on DEV Community and was authored by Gentrit Biba
Jest is a popular testing framework maintained by Facebook that makes it easy to write and run tests for JavaScript applications. This guide will walk you through setting up Jest in your Node.js project from scratch.
Prerequisites
- Node.js installed on your system
- An existing Node.js project or a new one
Step 1: Initialize Your Project
If you don't have an existing project, create a new directory and initialize it:
mkdir my-node-project
cd my-node-project
npm init -y
Step 2: Install Jest
Install Jest as a development dependency:
npm install --save-dev jest
Step 3: Configure Jest in package.json
Update your package.json
to add Jest configuration and test script:
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
},
"jest": {
"testEnvironment": "node",
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"moduleFileExtensions": ["js", "json"],
"testMatch": ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"],
"verbose": true
}
}
Step 4: Create a Sample Function to Test
Create a new file called math.js
:
// math.js
function sum(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
module.exports = {
sum,
multiply
};
Step 5: Write Your First Test
Create a test file called math.test.js
:
// math.test.js
const { sum, multiply } = require('./math');
describe('Math functions', () => {
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
test('multiplies 3 * 4 to equal 12', () => {
expect(multiply(3, 4)).toBe(12);
});
});
Step 6: Additional Jest Configuration (Optional)
Create a jest.config.js
file for more detailed configuration:
// jest.config.js
module.exports = {
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: [
"/node_modules/"
],
// The test environment that will be used for testing
testEnvironment: "node",
// The glob patterns Jest uses to detect test files
testMatch: [
"**/__tests__/**/*.[jt]s?(x)",
"**/?(*.)+(spec|test).[tj]s?(x)"
]
};
Step 7: Running Tests
You can now run your tests using npm:
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage report
npm test -- --coverage
Common Jest Matchers
Here are some commonly used Jest matchers:
// Exact equality
expect(value).toBe(2);
// Object matching
expect(data).toEqual({id: 1});
// Truthiness
expect(value).toBeTruthy();
expect(value).toBeFalsy();
// Numbers
expect(value).toBeGreaterThan(3);
expect(value).toBeLessThan(5);
// Strings
expect(string).toMatch(/pattern/);
// Arrays
expect(array).toContain(item);
// Exceptions
expect(() => {
throw new Error('Wrong!');
}).toThrow('Wrong!');
Testing Asynchronous Code
Jest handles async code testing gracefully:
// Testing Promises
test('async test', () => {
return fetchData().then(data => {
expect(data).toBe('data');
});
});
// Using async/await
test('async test with async/await', async () => {
const data = await fetchData();
expect(data).toBe('data');
});
Best Practices
- File Organization: Keep test files close to the code they're testing
src/
├── math.js
└── __tests__/
└── math.test.js
Test Isolation: Each test should be independent and not rely on other tests
Meaningful Descriptions: Use clear test descriptions
describe('User authentication', () => {
test('should successfully log in with valid credentials', () => {
// test code
});
});
- Setup and Teardown: Use Jest's lifecycle methods when needed
beforeAll(() => {
// Setup before all tests
});
afterEach(() => {
// Cleanup after each test
});
Conclusion
You now have a fully configured Jest testing environment in your Node.js application. Remember to:
- Write tests as you develop new features
- Aim for high test coverage
- Run tests frequently
- Keep tests maintainable and readable
Your tests will help catch bugs early, serve as documentation, and make refactoring easier.
This was fun! I write about stuff like this all the time on my blog. Swing by if you're into coding, math puzzles, and that kind of thing: blog.gentrit.dev
This content originally appeared on DEV Community and was authored by Gentrit Biba
Gentrit Biba | Sciencx (2024-11-08T00:55:34+00:00) Setting Up Jest Testing in Your Node.js Application: A Complete Guide. Retrieved from https://www.scien.cx/2024/11/08/setting-up-jest-testing-in-your-node-js-application-a-complete-guide/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.