DEV Community

Cover image for Automate Testing and Release of npm Packages with GitHub Actions
Rodrigo Burgos
Rodrigo Burgos

Posted on

Automate Testing and Release of npm Packages with GitHub Actions

Still some working to be done, such as release control within github itself. Maybe i'll update this post later with these features.

Step 1: Creating an npm Authentication Token

To publish your package from GitHub Actions, you need an authentication token:

Go to npmjs.com.

Log in and navigate to Access Tokens in your profile settings.

Click Generate New Token with at least Publish access.

Copy the generated token.

In your GitHub repository, go to Settings > Secrets and variables > Actions.

Click New repository secret, name it NPM_TOKEN, and paste the token.

Step 2: Setting Up GitHub Actions Workflow

Create a .github/workflows/test-and-publish.yml file in your repository with the following content:

name: Test and Publish

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout repository
      uses: actions/checkout@v3

    - name: Set up Node.js
      uses: actions/setup-node@v3
      with:
        node-version: '20'

    - name: Install dependencies
      run: yarn install --frozen-lockfile

    - name: Run tests
      run: yarn test

  publish:
    needs: test
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main' && github.event_name == 'push'

    steps:
    - name: Checkout repository
      uses: actions/checkout@v3

    - name: Set up Node.js
      uses: actions/setup-node@v3
      with:
        node-version: '20'
        registry-url: 'https://registry.npmjs.org/'

    - name: Install dependencies
      run: yarn install --frozen-lockfile

    - name: Publish to npm
      run: yarn publish --access public
      env:
        NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
Enter fullscreen mode Exit fullscreen mode

Explanation of Workflow

  1. Runs on every push and pull request to main.

  2. Checks out the repository.

  3. Sets up Node.js version 20.

  4. Installs dependencies using yarn install --frozen-lockfile to ensure dependency consistency.

  5. Runs tests using yarn test.

  6. Publish Job

  7. Runs only if tests pass and the event is a push to main.

  8. Ensures a clean checkout of the repository.

  9. Sets up Node.js with the npm registry.

  10. Installs dependencies.

  11. Publishes the package using yarn publish --access public.

Committing and Running the Workflow

  1. Commit and push the .github/workflows/test-and-publish.yml file to your repository. Once pushed:

  2. GitHub Actions will trigger a test run.

  3. If the tests pass and the branch is main, the package will be published to npm automatically.

Top comments (0)