Skip to content

Run your tests on every push

BasicsBuild alongGitHub ActionsYou need: a GitHub repository
What you’ll build: A workflow that checks out your code on a clean machine, installs it, runs the tests on every push and pull request, and shows the result. Seven steps, each with a command that proves it worked.push runs on mainPR checks every pull requestnpm ci clean install from the lockfilered a failing test blocks the mergegreen a passing badge on the README
Step 1 of 7

Start with a project whose tests pass

In your repository, add package.json, a small cart.js and its tests in cart.test.js. The tests use node:test, which ships with Node, so there is nothing to download.

Run npm install once. With no dependencies it installs nothing, but it writes package-lock.json, which CI will need.

WHY

CI runs the same command you run. If npm test is not green on your laptop, a pipeline only tells you the same thing more slowly.

This step runs:
terminal
$ npm install
package.jsonnew+9−0
Added: {
Added: "name": "shop",
Added: "version": "1.0.0",
Added: "private": true,
Added: "type": "module",
Added: "scripts": {
Added: "test": "node --test"
Added: }
Added: }
cart.jsnew+4−0
Added: // Prices are in cents, so the sums stay exact.
Added: export function total(items) {
Added: return items.reduce((sum, item) => sum + item.price * item.qty, 0);
Added: }
cart.test.jsnew+15−0
Added: import { test } from 'node:test';
Added: import assert from 'node:assert/strict';
Added: import { total } from './cart.js';
Added:
Added: test('an empty cart costs nothing', () => {
Added: assert.equal(total([]), 0);
Added: });
Added:
Added: test('adds price times quantity', () => {
Added: const items = [
Added: { price: 250, qty: 2 },
Added: { price: 100, qty: 1 },
Added: ];
Added: assert.equal(total(items), 600);
Added: });