Frontend Development 16 min read

A Comprehensive Guide to Frontend Unit Testing with Jest and Mocha

This article introduces the importance of frontend unit testing, presents survey data on current practices, compares popular frameworks like Jest and Mocha, provides step‑by‑step setup instructions, demonstrates code examples for JavaScript, TypeScript and async functions, and explains how to generate coverage reports and use common assertions.

政采云技术
政采云技术
政采云技术
A Comprehensive Guide to Frontend Unit Testing with Jest and Mocha

The article begins with an introduction explaining why unit testing is essential for modern JavaScript projects, highlighting the lack of static type checking, the need for correctness, automation, and safe refactoring.

Why Frontend Needs Unit Testing?

JavaScript lacks type checking, so tests catch runtime errors.

Tests verify code correctness before release.

Automated tests can be run repeatedly, improving efficiency.

Test suites protect code quality during rapid refactoring.

Current Situation

A survey of 200 developers (70 responses) shows that 81% of respondents are frontend developers, with larger organizations adopting unit testing more frequently.

Common Unit Testing Tools

The most used frameworks are Mocha and Jest, but Jest is recommended due to higher GitHub stars, issues, and npm download counts.

Framework Comparison

Framework

Assertions

Async Support

Coverage

Mocha

Not built‑in (requires extra library)

Friendly

Not built‑in

Jest

Built‑in

Friendly

Supported

Jest offers out‑of‑the‑box support, making it the preferred choice.

Example: Testing a sum Function

File: ./sum.js

function sum(a, b) {
  return a + b;
}
module.exports = sum;

Mocha + Chai

File: ./test/sum.test.js

const { expect, assert } = require('chai');
const sum = require('../sum');

describe('sum', function() {
  it('adds 1 + 2 to equal 3', () => {
    assert(sum(1, 2) === 3);
  });
});

Jest

File: ./test/sum.test.js

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

describe('sum function test', () => {
  it('sum(1, 2) === 3', () => {
    expect(sum(1, 2)).toBe(3);
  });
  test('sum(1, 2) === 3', () => {
    expect(sum(1, 2)).toBe(3);
  });
});

Getting Started

1. Install Dependencies

npm install --save-dev jest

2. Simple Example

Create ./sum.js (as shown above) and a test file ./test/sum.test.js (Jest example). Add the following script to package.json :

{
  "scripts": {
    "test": "jest"
  }
}

Run npm run test to see the results.

3. ES6 Support

Node uses CommonJS; to use import syntax, install Babel:

npm install --save-dev @babel/core @babel/preset-env

Add a .babelrc file:

{ "presets": ["@babel/preset-env"] }

4. TypeScript Support

npm install --save-dev @babel/preset-typescript

Update .babelrc to include the TypeScript preset and install @types/jest for type definitions.

5. Continuous Watch

"scripts": { "test": "jest --watchAll" }

6. Generating Coverage Reports

Add a jest.config.js file:

module.exports = {
  collectCoverage: true,
  collectCoverageFrom: ['get.ts', 'sum.ts', 'src/utils/**/*'],
  coverageThreshold: {
    global: {
      statements: 90,
      functions: 90,
      branches: 90,
    }
  }
};

Run tests with coverage enabled to see percentages for statements, branches, functions, and lines.

Common Assertion Methods

.not – asserts inequality.

.toEqual – deep equality for objects.

.toHaveLength – checks length of strings or arrays.

.toThrow – expects a function to throw an error.

.toMatch – regex matching for strings.

.toContain – checks if an array contains a value.

Testing Asynchronous Functions

Example async function fetchUser returns a Promise after a timeout. Test with Jest using async/await :

test('fetchUser() returns a user named moji', async () => {
  const data = await fetchUser();
  expect(data.name).toBe('moji');
});

If Babel does not support async/await, install @babel/plugin-transform-runtime and add it to the Babel plugins.

Conclusion

The article provides a complete walkthrough of frontend unit testing, from motivation and tool selection to configuration, writing tests for JavaScript, TypeScript, and async code, generating coverage reports, and using a variety of Jest assertions, enabling readers to confidently integrate unit testing into their projects.

frontendJavaScriptTestingunit testingJestCoveragemocha
政采云技术
Written by

政采云技术

ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.