Unit Testing Tool‐JEST - JUCSE49-Mavericks/Smart-Class-Routine-Management-System GitHub Wiki
Author
: Jannati Tajrimin Mitu

Jest is an open-source testing framework maintained by Facebook, primarily designed for testing JavaScript applications. It is widely used for unit, integration, and snapshot testing in Node.js, React, and other JavaScript projects. Jest requires zero configuration and supports small to large applications seamlessly.
- Key Features
- Installation and Setup
- Writing Tests with Jest
- Running Tests
- Jest Assertions
- Mocking in Jest
- Code Coverage
- Best Practices
- References
Feature | Description |
---|---|
Zero Configuration | Works out of the box without extra setup. |
Mocking & Spies | Mock functions and modules for better isolation. |
Snapshot Testing | Track UI changes with snapshots. |
Asynchronous Testing | Supports promises, callbacks, and async/await. |
Code Coverage Reporting | Built-in reports for test coverage. |
Parallel Test Execution | Runs tests in parallel to boost performance. |
TypeScript Support | Works with ES6+ and TypeScript. |
- Node.js: Ensure Node.js and npm are installed.
- JavaScript Project: Jest works with new or existing projects.
# Using npm
npm install --save-dev jest
# Using yarn
yarn add --dev jest
"scripts": {
"test": "jest"
}
For advanced setups, use jest.config.js
:
module.exports = {
verbose: true,
testEnvironment: "node",
};
A typical Jest test file has .test.js
or .spec.js
extension.
// 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);
});
-
test()
: Defines a test case. -
expect()
: Asserts the expected outcome. -
.toBe()
: Strict equality matcher.
Run tests using:
npm test
Alternatively, run with Jest CLI:
npx jest
-
--watch
: Run tests in watch mode. -
--coverage
: Generate code coverage reports. -
--verbose
: Display detailed test results.
Matcher | Description |
---|---|
.toBe() |
Strict equality comparison. |
.toEqual() |
Deep equality for objects or arrays. |
.toBeNull() |
Checks if a value is null . |
.toBeDefined() |
Verifies if a value is defined. |
.toHaveLength() |
Checks length of arrays or strings. |
test('object assignment', () => {
const data = { one: 1 };
data['two'] = 2;
expect(data).toEqual({ one: 1, two: 2 });
});
Mocking helps isolate tests by replacing dependencies with mock functions.
const myMock = jest.fn().mockReturnValueOnce(10).mockReturnValueOnce(20);
console.log(myMock()); // 10
console.log(myMock()); // 20
jest.mock('./myModule');
const myModule = require('./myModule');
test('mocked function call', () => {
myModule.someFunction.mockReturnValue('mocked value');
expect(myModule.someFunction()).toBe('mocked value');
});
Generate code coverage reports with:
npx jest --coverage
This will create a coverage
folder containing metrics like:
- Statements Covered
- Branches Tested
- Functions Covered
- Lines Covered
- Isolate Tests: Ensure tests run independently.
- Use Mocking Carefully: Mock external dependencies only when necessary.
- Write Descriptive Test Names: Test names should reflect the purpose clearly.
-
Group Tests: Use
describe()
to group related tests. - Run Tests Frequently: Use watch mode to catch bugs early.
This table provides a detailed comparison of Jest, Mocha, and Jasmine across key criteria to help developers understand when Jest is the optimal choice.
Criteria | Jest | Mocha | Jasmine |
---|---|---|---|
Configuration | Zero-config, works out-of-the-box. | Requires setup and configuration. | Minimal setup, but requires some tweaking. |
Performance | Runs tests in parallel by default. | Single-threaded; slower without tuning. | No built-in parallel support. |
Built-in Features | Comes with spies, mocks, and assertions. | Requires additional libraries (e.g., Chai, Sinon). | No built-in mocks, spies must be manually created. |
Community & Ecosystem | Highly popular in React/Node.js projects. | Strong community but requires more dependencies. | Smaller community but stable. |
Asynchronous Code Testing | Native support for async/await. | Requires more boilerplate for async code. | Async support available, but with quirks. |
Snapshot Testing | Built-in support for snapshot testing. | No built-in snapshot support. | No snapshot support. |
Code Coverage | Code coverage built-in. | Requires nyc or istanbul integration. |
No built-in coverage; external tools needed. |
Ease of Use | Simplifies testing with integrated tools. | Requires separate libraries for assertions, spies, and mocks. | Basic API, but can feel less modern. |
Use Case Suitability | Ideal for React, Node.js, and TypeScript projects. | Best for highly customized testing setups. | Good for legacy systems or simple unit tests. |
Learning Curve | Easier for beginners with simple APIs. | Requires learning multiple tools (e.g., Mocha + Chai + Sinon). | Moderate; fewer dependencies but limited features. |
Jest excels in projects where simplicity and built-in features are essential. It’s especially powerful for React and Node.js applications, thanks to zero-config support and snapshot testing. While Mocha and Jasmine have their strengths, Jest offers an all-in-one testing solution that reduces the need for extra tools or libraries.