Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 43 ยท Quality and Operations

ESLint, Prettier and the Test Pyramid for Express

Set up ESLint and Prettier for an Express project, learn what the test pyramid means for APIs, run unit and integration tests, and try routes with curl, Postman or Insomnia.

Working code is the minimum. Good code is code that a teammate (or you, six months from now) can read, change and trust. Three habits get you most of the way there, and all of them can be automated:

  1. A linter (ESLint) that catches bugs and bad patterns before the code runs.
  2. A formatter (Prettier) that ends arguments about spacing and quotes.
  3. Tests arranged sensibly: many fast ones, a few slow ones. This arrangement is called the test pyramid.

On top of those, you need a comfortable way to try routes by hand while building them. This lesson covers all four for an Express project. The tools themselves (ESLint, Prettier, Postman) are not installable in this site's runner, so their configuration is shown read-only, while the testing ideas run live.

Four layers of quality

ESLint Finds mistakes and risky code.
Prettier One consistent code style.
Tests Prove behavior stays correct.
API client Try routes by hand.
1 / 2

ESLint: catch problems early

ESLint reads your JavaScript and reports problems without running it: variables that are never used, typos in names, == where === was meant, a promise that nobody awaits. In an Express app it also helps with rules like "do not leave console.log in routes" or "always handle the error argument".

Set it up with the current flat config file, eslint.config.js (read-only, needs npm install -D eslint @eslint/js globals):

JavaScript
// eslint.config.js
import js from '@eslint/js';
import globals from 'globals';

export default [
  js.configs.recommended,                    // the sensible default rules
  {
    files: ['**/*.js'],
    languageOptions: {
      ecmaVersion: 'latest',
      sourceType: 'module',                  // we use import/export
      globals: { ...globals.node },          // process, Buffer, __dirname-free Node globals
    },
    rules: {
      'no-unused-vars': ['error', { argsIgnorePattern: '^_' }],  // (req, _res) is allowed
      eqeqeq: 'error',
      'no-console': ['warn', { allow: ['warn', 'error'] }],
      'prefer-const': 'error',
    },
  },
  { ignores: ['node_modules/', 'coverage/', 'dist/'] },
];

Then add scripts to package.json and run them:

JSON
{
  "scripts": {
    "lint": "eslint .",
    "lint:fix": "eslint . --fix"
  }
}

npm run lint lists problems with file and line numbers; --fix repairs the ones that have an automatic fix.

Bugs a linter finds in Express code

JavaScript
app.get('/users/:id', async (req, res) => {
  const user = await findUser(req.params.id)
  if (user == null) {                      // eqeqeq: prefer === (user === null || user === undefined)
    res.status(404).json({ error: 'not found' });
    // missing "return": the next line still runs and tries to send a second response
  }
  res.json(user);
  const unused = 5;                        // no-unused-vars
});

app.use((err, req, res) => {               // only three parameters: Express will NOT treat this as an error handler
  res.status(500).json({ error: 'oops' });
});

Two of those are Express-specific traps. A forgotten return after sending a response leads to the dreaded "Cannot set headers after they are sent" error (The Response Object). And an error handler needs exactly four parameters (Error Handling); with three, it is silently ordinary middleware. Plugins such as eslint-plugin-n (Node rules) and eslint-plugin-security add more checks, and TypeScript projects add typescript-eslint. The no-floating-promises rule from typescript-eslint is especially useful for async code.

Introduce the linter on day one. Adding it to a large existing project produces hundreds of warnings at once, and teams then switch the rules off instead of fixing the code.

Prettier: stop arguing about style

Prettier rewrites your code in one fixed style: indentation, quotes, line width, trailing commas, line breaks. It has few options on purpose. Developers stop debating style, and diffs show real changes, not formatting noise.

JSON
// .prettierrc
{
  "singleQuote": true,
  "semi": true,
  "printWidth": 100,
  "trailingComma": "all"
}
JSON
{
  "scripts": {
    "format": "prettier --write .",
    "format:check": "prettier --check ."
  }
}

format rewrites files; format:check only reports (use it in CI). ESLint and Prettier have different jobs: ESLint finds bugs and bad practice, Prettier handles layout. Install eslint-config-prettier so ESLint does not complain about style rules that Prettier owns.

Automating it

  • In the editor: VS Code's "Format on Save" with the Prettier extension, plus the ESLint extension.
  • Before every commit: a git hook (with a tool like husky and lint-staged) runs eslint --fix and prettier --write only on staged files, so bad code never enters the repository.
  • In CI: run npm run lint, npm run format:check and npm test on every pull request (Deployment covers CI/CD ideas).

The test pyramid for an Express app

Not all tests are equal. Some run in milliseconds and pin down one function; others start a whole server and a database and take seconds. The test pyramid says to write many of the fast, narrow tests at the bottom and few of the slow, broad tests at the top.

flowchart TB
  E2E["End-to-end: a few<br/>real browser or real services"]
  INT["Integration: some<br/>HTTP requests against the app"]
  UNIT["Unit: many<br/>pure functions, services, validators"]
  E2E --- INT --- UNIT

Wide base, narrow top: the closer to the bottom, the faster, cheaper and more numerous the tests.

Layer What it tests in Express Speed Count
Unit A pure function, a service with a fake repository, a validator, a middleware called with fake req/res/next microseconds hundreds
Integration The real app (routes, middleware, error handler) through real HTTP calls, with a test database or an in-memory store milliseconds dozens
End to end The deployed system through a browser or a full client: login, checkout, the happy paths that make money seconds a handful

The shape matters because of cost. Unit tests tell you exactly which function broke; end-to-end tests tell you that something broke, slowly. A pyramid turned upside down (mostly browser tests, few unit tests) is slow, flaky and expensive to maintain.

Make code easy to test

The architecture from Testing Express Apps and Writing Your Own Middleware pays off here:

  • Keep business rules in plain functions that take values and return values, not entangled with req and res.
  • Inject dependencies (a repository, a clock) instead of importing them inside the function.
  • Export the app separately from app.listen, so tests can start it on a free port.

Unit tests

The first example tests a small piece of business logic and a middleware function with a fake request. It uses only node:assert and a tiny test() helper so the output is easy to read; with the real runner the same bodies live inside node:test or Vitest/Jest test() blocks.

Node.js Unit tests: a pure function, a service and a middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

All of these run in well under a millisecond each, with no server, no network and no database. The last test fails on purpose so you can see what a failure report looks like: the message says what was expected and what the code returned.

Integration tests

An integration test sends a real HTTP request to the real app and checks the response. It exercises routing, parsers, validation and the error handler together, which unit tests cannot. With real Express you would use supertest, which wraps this pattern: await request(app).get('/books').expect(200). The version below does the same with built-in fetch against a small stand-in app so you can see what is happening.

Node.js Integration tests with real HTTP requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the design choices: createApp(store) builds a fresh application per test, so no test depends on another; the helper starts on port 0 (a free port); and each test asserts on the status code and the body, the contract a client relies on. These are the same habits you will use with supertest and a test database (Testing Express Apps).

End-to-end tests

At the top of the pyramid, tools such as Playwright drive a real browser against a running instance of your app and check the whole user journey: sign up, add to cart, pay. Keep this layer small: a handful of tests for the flows that must never break. For a pure API there may be no browser layer at all; a "contract test" that calls the deployed staging API with a real token plays the same role.

Measuring: coverage

A coverage report shows which lines your tests execute (node --test --experimental-test-coverage, or c8/Vitest/Jest coverage). It is useful for finding untested code, such as an error branch nobody triggered. It is not a quality score: 100% coverage with weak assertions proves little. Aim for solid coverage on business logic and error paths, not a number.

Trying routes by hand: curl, Postman and Insomnia

While you build an endpoint you want to call it without writing a test first. Browsers only make GET requests easily, so use an API client:

  • curl, on every machine, scriptable and ideal for documentation:
Terminal
curl -i http://localhost:3000/books
curl -i -X POST http://localhost:3000/books \
  -H "Content-Type: application/json" \
  -d '{"title":"Dune"}'
curl -i -H "Authorization: Bearer $TOKEN" http://localhost:3000/me

-i shows the status line and headers, which is exactly what you need while debugging.

  • Postman and Insomnia (and the lighter, file-based Bruno) are graphical clients. You save requests in collections, switch between environments ({{baseUrl}} set to local, staging or production), store tokens in variables, add simple assertions and share collections with the team. Postman can run a collection from the command line (Newman), which turns a manual collection into an automated smoke test.
  • VS Code REST Client, or the built-in HTTP file support in JetBrains editors, lets you keep requests in a plain requests.http file inside the repository:
HTTP
### Create a book
POST http://localhost:3000/books
Content-Type: application/json

{ "title": "Dune" }

### List books
GET http://localhost:3000/books

Whichever you pick, put a few sample requests in the repository so new teammates can try the API in a minute. Exploration with a client and automated tests complement each other: the client is for discovery, tests are for regression.

Never commit real tokens, passwords or production URLs inside saved requests or exported collections. Use environment variables in the client and keep secrets out of the repository (Security Best Practices).

A sensible checklist

  • eslint.config.js and .prettierrc committed; lint, format:check and test scripts in package.json.
  • A pre-commit hook that lints staged files; CI that runs all three on every pull request.
  • Unit tests for business rules and middleware, integration tests for each route's happy path and main error paths, a few end-to-end checks.
  • App and server split, dependencies injected, a fresh app or store per test.
  • A requests.http file or a shared collection with example calls.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between ESLint and Prettier?

    A linter analyzes code quality and correctness; a formatter only changes layout.
  2. 2. What does the test pyramid recommend?

    Fast, narrow tests give precise feedback cheaply; slow broad tests are kept for the critical journeys.
  3. 3. Why should each integration test build a fresh app and store?

    Shared state between tests makes failures depend on execution order and hard to diagnose.
  4. 4. An error-handling middleware is written as (err, req, res) => {...}. What does the linter-friendly fix involve?

    With only three parameters Express treats the function as ordinary middleware, so errors skip it.
  5. 5. Which is a good use of Postman or Insomnia in a project?

    API clients are for exploration and sharing examples; automated tests are still needed for regression.

Summary

  • ESLint (flat eslint.config.js) finds bugs such as missing return after a response and error handlers with the wrong arity; Prettier gives every file the same layout.
  • Automate both: format on save, a pre-commit hook for staged files, and CI on every pull request.
  • The test pyramid: many fast unit tests, some integration tests that make real HTTP calls to the app, a few end-to-end journeys.
  • Design for testability: pure functions, injected dependencies, an exported app separate from listen, a fresh app and store per test.
  • Coverage finds untested code but is not a quality guarantee.
  • Use curl, Postman, Insomnia, Bruno or .http files to try routes, with secrets kept in environment variables.

Next: write real tests in Testing Express Apps, or review the safe defaults in Security Best Practices.