ยท best practices

Create a TypeScript test matrix using GitHub Actions

GitHub workflows are a great way to set up a continuous integration pipeline. You can define jobs within a workflow and use GitHub's runners to execute those jobs. These runners can be hosted on GitHub's infrastructure or your own. In this tutorial, you'll learn how to use a matrix strategy to run jobs concurrently using different runner images.

GitHub workflows provide an excellent platform for setting up a continuous integration pipeline. Within a workflow, you can define one or more jobs. GitHub provides virtual machines, referred to as runners, for executing jobs in a GitHub Actions workflow. These runners can be hosted either on GitHub's infrastructure (GitHub-hosted runners) or your own infrastructure (self-hosted runners).

In this tutorial, you will learn how to use a matrix strategy to run jobs concurrently using different runner images. This approach enables you to test your TypeScript code across different operating systems or configurations, such as different versions of Node.js.

Contents

Setting Up a Basic Workflow

Let's begin by setting up a basic workflow that runs on a single virtual machine hosted by GitHub. We'll use the latest stable Ubuntu version provided by GitHub as the runner image, and you can find more details about the available images in the actions/runner-images repository.

In our workflow, we'll use the npm ci command, which is similar to npm install, but designed for continuous integration systems. In contrast to npm install, it directly installs dependencies from the package-lock.json file and avoids adding any missing dependencies. If you're familiar with Yarn, you might recognize this behavior from yarn install --frozen-lockfile.

name: 'Test'
 
on: ['pull_request', 'push']
 
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 18
      - run: |
          npm ci
          npm run build --if-present
          npm test

Cross-Version Testing with Matrix Strategy

To demonstrate our TypeScript testing process, we aim to execute the same workflow across various versions of Node.js. Achieving this requires implementing a matrix strategy. With this approach, we can define custom keys, such as os and node-version, which can then be referenced in our runs-on workflow syntax or used as an argument in our Node.js setup:

name: 'Test'
 
on: ['pull_request', 'push']
 
jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest]
        node-version: [16, 18]
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node-version }}
      - run: |
          npm ci
          npm run build --if-present
          npm test
Back to Blog