Chapter 12 · Lesson 3 of 10
CI/CD and automation

Run tests on every push and pull request with GitHub Actions

To run tests on every push and pull request, add a workflow with on push and pull_request triggers that checks out the code, installs with npm ci and runs npm test.

By the end you will

Add a Node test workflow that runs on every push and pull request, cancels stale runs and can be required before merge.

Time
15 min
Level
Beginner
Check
4 questions
You need
  • A GitHub repository with a Node project and an npm test script
  • A package-lock.json committed to the repo

The simplest useful pipeline runs your tests every time someone pushes or opens a pull request. You add one workflow file, and GitHub shows a green check or a red cross next to every commit and pull request. This lesson uses a Node project, but the shape is the same for any language: check out, set up the toolchain, install, test. Read GitHub Actions workflow anatomy first if the keys below are new.

How it works#

The push trigger runs on commits to branches you choose. The pull_request trigger runs on the merge result of a pull request, so you test what would land on the target branch. Running both gives feedback while you work on a branch and a final check on the PR. The job runs on a fresh Ubuntu runner, installs dependencies from the lockfile, and runs your test script. A non-zero exit code fails the job, and that failure becomes a status check on the commit. If you protect the branch, a required status check turns that signal into a gate.

Step 1: Check your project locally#

Confirm the commands work on your own machine first:

bash
npm ci
npm test

CI will run exactly these. If npm test is missing from package.json, add a scripts.test entry. Commit package-lock.json, because npm ci needs it.

Step 2: Create the workflow#

Create .github/workflows/test.yml:

yaml
name: test

on:
  push:
    branches: [main]
  pull_request:

concurrency:
  group: test-${{ github.ref }}
  cancel-in-progress: true

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npm test

What each part does:

  • branches: [main] limits the push trigger to main. Feature branches are covered by pull_request, so you avoid running twice for the same commit.
  • concurrency groups runs by the git ref. A new push to the same branch cancels the run still going. That saves waiting on a commit you have already replaced.
  • permissions: contents: read gives the token only read access to the code.
  • actions/setup-node@v4 installs the Node version you name. Pin it so CI does not drift from your laptop.
  • npm ci installs from the lockfile and fails if package.json and the lockfile disagree.

Use ubuntu-latest unless you need another OS. If your tests need a database, run it as a service container in the job or start it with Docker Compose, and keep the test config free of production credentials.

Step 3: Push and watch the run#

bash
git checkout -b add-ci
git add .github/workflows/test.yml
git commit -m "ci: run tests on push and pull request"
git push -u origin add-ci

Open a pull request. The Checks section at the bottom of the PR shows the test job. Click Details to open the log. The same run appears under the Actions tab. Fix any failure by reading the red step, pushing a new commit, and watching the new run replace the old one.

Step 4: Make the check required#

A green check that you may ignore is advice. In the repository settings, add a branch protection rule or ruleset for main and select the test check as required. After that the merge button stays disabled until the job passes. The names must match exactly, which matters more when you use a matrix. See Matrix builds and branch protection.

Step 5: Know what fork pull requests get#

When a contributor opens a pull request from a fork, the run uses their code, so GitHub treats it as untrusted. Repository secrets are not passed, and the GITHUB_TOKEN is read-only. Your tests must therefore pass with no secrets. Mock external services, use test fixtures, and keep real credentials for the deploy workflow that runs only on your own branches. Secrets and variables in CI pipelines explains why you should not work around this.

First-time contributors may also need a maintainer to approve the run before it starts, depending on your repository settings.

Check it worked#

On a pull request you should see a check named test with a green tick, and the log should show npm ci followed by your test output. Push a second commit quickly after the first and confirm the first run shows as cancelled. Break a test on purpose in a throwaway branch and confirm the check turns red and the merge button is blocked once the check is required.

Edge cases and gotchas#

  • Tests that pass locally but fail in CI. Common causes are a different Node version, a missing environment variable, a timezone assumption or a test that depends on files ignored by git. Print node --version in the log to compare.
  • Running twice. If push has no branch filter and pull_request is also set, a PR branch commit starts two runs. The filter above avoids that.
  • Cancel-in-progress on deploys. It is right for tests and wrong for deploys. Cancelling a half-finished deploy can leave a server in a mixed state. Use cancel-in-progress: false for deploy groups.
  • Lockfile drift. If someone edits package.json without updating the lockfile, npm ci fails with an error. That is the point. Run npm install locally and commit the lockfile.
  • Flaky tests. A test that sometimes fails teaches people to re-run. Fix it, or quarantine it, rather than adding automatic retries everywhere.
  • Secrets in test output. Do not print environment dumps in tests. Logs on public repositories are public.

Troubleshooting#

SymptomLikely causeFix
npm ERR! The npm ci command can only install with an existing package-lock.jsonLockfile not committedRun npm install locally and commit package-lock.json
npm ci fails with a lockfile out of sync messagepackage.json changed without the lockfileRegenerate the lockfile and commit both
Missing script: "test"No test script in package.jsonAdd "test" under scripts
Check never appears on the PRWorkflow file not on the base branch or wrong triggerCheck the path and on block
Fork PR fails on an API callTest needs a secret that forks do not getMock the call, or skip that test for forks
Two runs per commitpush and pull_request both matchLimit push to main
Required check stays pending foreverCheck name in the rule does not match the jobUse the exact job name shown on the PR

Quick reference#

yaml
on:
  push:
    branches: [main]
  pull_request:
concurrency:
  group: test-${{ github.ref }}
  cancel-in-progress: true
permissions:
  contents: read
steps:
  - uses: actions/checkout@v4
  - uses: actions/setup-node@v4
    with:
      node-version: 20
  - run: npm ci
  - run: npm test

Next#

Continue with Build and push a Docker image to GHCR.

Check what you learned4 questions
1Which command should CI use to install Node dependencies?
2What happens to repository secrets in a pull_request run from a fork?
3What does cancel-in-progress: true do in a concurrency group?
4How do you make a green test run block a merge?

Frequently asked questions

How do I run npm test on every push in GitHub Actions?

Create .github/workflows/test.yml with on push and pull_request, a job on ubuntu-latest, then steps for actions/checkout@v4, actions/setup-node@v4, npm ci and npm test.

Why use npm ci instead of npm install in CI?

npm ci installs exactly what package-lock.json lists and fails if the lockfile and package.json disagree. It also starts from a clean node_modules, so runs are repeatable.

Do secrets work in pull requests from forks?

No. For pull_request events from a fork, GitHub does not pass repository secrets and gives the token read-only access. Tests must pass without secrets.

How do I cancel old workflow runs when I push again?

Add a concurrency group with cancel-in-progress: true. A new run in the same group cancels the one still in progress.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios