Search code examples
node.jsgithubgatsbyworkflowgithub-actions

How to create a workflow to deploy on a React & Gatsby app to Github pages?


I created a workflow to automatically do npm run deploy whenever I push something to the main branch of my repo in order to keep the Github page's website updated.

# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions

name: Node.js CI

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [12.x, 14.x, 16.x]
        # See supported Node.js release schedule at https://nodejs.org/en/about/releases/

    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm'
    - run: npm ci
    - run: npm run build --if-present
    - run: npm test
    
    - name: Deploy
      run: |
        git config --global user.name $user_name
        git config --global user.email $user_email
        git remote set-url origin https://${github_token}@github.com/${repository}
        npm run deploy
      env:
        user_name: 'github-actions[bot]'
        user_email: 'github-actions[bot]@users.noreply.github.com'
        github_token: ${{ secrets.ACTIONS_DEPLOY_ACCESS_TOKEN }}
        repository: ${{ github.repository }}

So basically I used the default node.js workflow and added the part concerning Github pages but the workflow keep failing.

I have the following errors :

build(12.x) 
 npm test
  shell: /usr/bin/bash -e {0}

> react-portfolio@0.1.0 test /home/runner/work/my-portfolio/my-portfolio
> echo "Write tests! -> https://gatsby.dev/unit-testing" && exit 1

Write tests! -> https://gatsby.dev/unit-testing
npm ERR! Test failed.  See above for more details.

How can I fix this ?


Solution

  • echo "Write tests! -> https://gatsby.dev/unit-testing" && exit 1

    This is the output when you run npm run test by default (in most of starters):

    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1"
    

    Basically, this is prompting the echo message and is exiting the operation (&& exit 1). That's why your workflow is breaking.

    So, for your current use-case, I would just leave the workflow like:

       - name: Use Node.js ${{ matrix.node-version }}
          uses: actions/setup-node@v2
          with:
            node-version: ${{ matrix.node-version }}
            cache: 'npm'
        - run: npm ci
        - run: npm run build --if-present
    

    In the future, if you run tests, you will need to change the command to add your custom unit tests without skipping the process.