Courses / Frontend Testing
1. Setting up Jest for unit testing
Installing and configuring Jest for a JavaScript/TypeScript project and basic test script.
How It Works
Think of Jest as a test workshop: you add test files (blueprints), Jest reads them, sets up an isolated environment, runs the checks, and returns a pass/fail report along with helpful diffs if something changed.
Install Jest as a dev dependency (npm install --save-dev jest).
Add a test script in package.json like "test": "jest".
Write test files named *.test.js or *.spec.js (or configure patterns) and export/import code to test.
Run npm test, which invokes Jest to discover and run tests and print the report.
See It
The code exports a simple sum function and a Jest test that imports it and asserts sum(2,3) === 5. When you run npm test, Jest loads sum.test.js, executes the test callback, and reports success because the result equals 5. Try changing the expected value to 6 to see a failing test and the assertion diff.
/*
Run these commands in an empty folder to try:
npm init -y
npm install --save-dev jest
Add "test": "jest" to package.json scripts
Create sum.js and sum.test.js as below, then run: npm test
*/
// sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
// sum.test.js
const sum = require('./sum');
test('adds 2 + 3 to equal 5', () => {
expect(sum(2, 3)).toBe(5);
});Use It
Adding regression checks for a library function before releasing a new patch.
// config.js
function getConfig(env) {
return env === 'prod' ? { logging: false } : { logging: true };
}
module.exports = getConfig;
// config.test.js
const getConfig = require('./config');
test('prod has logging off', () => {
expect(getConfig('prod').logging).toBe(false);
});
test('dev has logging on', () => {
expect(getConfig('dev').logging).toBe(true);
});Jest lets you automatically and repeatedly verify behavior (dev vs prod config) so changes can't silently break environment-specific logic.
Break It
What will happen when you run these tests with Jest?
// calculator.js
exports.multiply = (a, b) => a * b;
// calculator.test.js
const { multiply } = require('./calculator');
describe('multiply', () => {
test('multiplies positive numbers', () => {
expect(multiply(2, 3)).toBe(6);
});
test('multiplies with jest mock', () => {
const mocked = jest.fn(multiply);
mocked(2, 3);
expect(mocked).toHaveBeenCalledWith(2, 3);
expect(mocked).toHaveReturnedWith(6);
});
});jest.fn(fn) by default creates a mock function that does not invoke the original implementation; it only records calls and return values you explicitly provide. So calling mocked(2,3) returns undefined unless you use jest.fn(fn).mockImplementation(fn) or mockImplementationOnce, or use jest.spyOn on an object method. The expectation toHaveReturnedWith(6) fails because the mock never returned 6.
Wrap the original implementation when creating the mock, e.g. use const mocked = jest.fn((a,b) => multiply(a,b)) or mocked.mockImplementation(multiply).
// calculator.js
exports.multiply = (a, b) => a * b;
// calculator.test.js
const { multiply } = require('./calculator');
describe('multiply', () => {
test('multiplies positive numbers', () => {
expect(multiply(2, 3)).toBe(6);
});
test('multiplies with jest mock that calls original', () => {
const mocked = jest.fn((a, b) => multiply(a, b)); // ensure it calls the real implementation
mocked(2, 3);
expect(mocked).toHaveBeenCalledWith(2, 3);
expect(mocked).toHaveReturnedWith(6);
});
});Level Up
jest.spyOn for modules/objects: replace or wrap specific object methods while preserving original behavior and allow restoring after tests.
setupFiles / setupFilesAfterEnv: run global setup (like polyfills, global mocks, or custom matchers) before your tests execute.
ts-jest or Babel integration: compile TypeScript/modern JS on the fly so Jest can run tests without a separate build step.
Prove It
Create a package.json script and two tests: one that checks a pure function result and one that uses a mock which calls the real implementation; both must pass with npm test.
JavaScript
Setting up Jest for unit testing
Jest is a test runner that runs your unit tests and reports pass/fail results for JavaScript/TypeScript projects.
"I want automated checks so I don't ship regressions after every change."
Jest is a zero-configuration test runner and assertion library that you install, configure, and run via npm/yarn to execute tests in your project. It finds files by name patterns, runs them in Node, and reports results with helpful assertions and snapshots.
"I want automated checks so I don't ship regressions after every change."
Jest is a zero-configuration test runner and assertion library that you install, configure, and run via npm/yarn to execute tests in your project. It finds files by name patterns, runs them in Node, and reports results with helpful assertions and snapshots.