# 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.

URL: https://levelrail.com/learn/ci-cd/run-tests-on-every-push-and-pull-request/
Updated: 2026-11-27

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](https://levelrail.com/learn/ci-cd/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](https://levelrail.com/learn/ci-cd/matrix-builds-and-branch-protection/)), 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](https://levelrail.com/learn/ci-cd/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](https://levelrail.com/learn/ci-cd/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

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `npm ERR! The npm ci command can only install with an existing package-lock.json` | Lockfile not committed | Run `npm install` locally and commit `package-lock.json` |
| `npm ci` fails with a lockfile out of sync message | `package.json` changed without the lockfile | Regenerate the lockfile and commit both |
| `Missing script: "test"` | No test script in package.json | Add `"test"` under scripts |
| Check never appears on the PR | Workflow file not on the base branch or wrong trigger | Check the path and `on` block |
| Fork PR fails on an API call | Test needs a secret that forks do not get | Mock the call, or skip that test for forks |
| Two runs per commit | `push` and `pull_request` both match | Limit push to main |
| Required check stays pending forever | Check name in the rule does not match the job | Use 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
```

## Related lessons

- [GitHub Actions workflow anatomy](https://levelrail.com/learn/ci-cd/github-actions-workflow-anatomy/)): the keys used in this file.
- [Cache dependencies in GitHub Actions](https://levelrail.com/learn/ci-cd/cache-dependencies-in-github-actions/)): make the install step faster.
- [Matrix builds and branch protection](https://levelrail.com/learn/ci-cd/matrix-builds-and-branch-protection/)): test several versions and require the check.
- [Git branches and merging](https://levelrail.com/learn/git/git-branches-and-merging/)): the branches and pull requests these triggers react to.
- [Secrets and variables in CI pipelines](https://levelrail.com/learn/ci-cd/secrets-and-variables-in-ci-pipelines/)): handling credentials safely.

## Next

Continue with [Build and push a Docker image to GHCR](https://levelrail.com/learn/ci-cd/build-and-push-docker-image-to-ghcr/)).

## 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

- [GitHub Docs, building and testing Node.js](https://docs.github.com/en/actions/tutorials/build-and-test-code/nodejs)
- [GitHub Docs, using concurrency](https://docs.github.com/en/actions/using-jobs/using-concurrency)
