This guide explains how to configure GitHub Actions to run unit tests across various operating systems and Node.js versions using a matrix strategy.
In this guide, you’ll learn how to configure a GitHub Actions workflow to run unit tests across multiple operating systems and Node.js versions by leveraging the matrix strategy. This approach generates a job for every combination of variables—such as nodejs_version and operating_system—while allowing you to exclude specific pairs.
First, we define a matrix with three Node.js versions (18, 19, 20) and two operating systems (ubuntu-latest, macos-latest), excluding the unwanted combination of Node.js 18 on macOS:
Copy
Ask AI
name: Run Unit Testson: workflow_dispatch: push: branches: - main - feature/*env: MONGO_URI: 'mongodb+srv://supercluster.d83jj.mongodb.net/superData' MONGO_USERNAME: ${{ vars.MONGO_USERNAME }} MONGO_PASSWORD: ${{ secrets.MONGO_PASSWORD }}jobs: unit-testing: name: Unit Testing strategy: matrix: nodejs_version: [18, 19, 20] operating_system: [ubuntu-latest, macos-latest] exclude: - nodejs_version: 18 operating_system: macos-latest runs-on: ubuntu-latest steps: - name: Checkout Repository uses: actions/checkout@v4 - name: Setup Node.js Version - 18 uses: actions/setup-node@v3 with: node-version: 18 - name: Install Dependencies run: npm install - name: Unit Testing run: npm test - name: Archive Test Result uses: actions/upload-artifact@v3
At this stage, both runs-on and node-version are hardcoded. In the next section, we’ll update them to use matrix variables.
Replace the hardcoded values with ${{ matrix.operating_system }} and ${{ matrix.nodejs_version }} so each job picks up the correct OS and Node.js version:
Copy
Ask AI
name: Run Unit Testson: workflow_dispatch: push: branches: - main - feature/*env: MONGO_URI: 'mongodb+srv://supercluster.d83jj.mongodb.net/superData' MONGO_USERNAME: ${{ vars.MONGO_USERNAME }} MONGO_PASSWORD: ${{ secrets.MONGO_PASSWORD }}jobs: unit-testing: name: Unit Testing strategy: matrix: nodejs_version: [18, 19, 20] operating_system: [ubuntu-latest, macos-latest] exclude: - nodejs_version: 18 operating_system: macos-latest runs-on: ${{ matrix.operating_system }} steps: - name: Checkout Repository uses: actions/checkout@v4 - name: Setup Node.js Version - ${{ matrix.nodejs_version }} uses: actions/setup-node@v3 with: node-version: ${{ matrix.nodejs_version }} - name: Install Dependencies run: npm install - name: Unit Testing run: npm test - name: Archive Test Result uses: actions/upload-artifact@v3
Each job will now automatically run on the specified operating system and install the appropriate Node.js version.