DEV Community

Nicolas Lepage
Nicolas Lepage

Posted on

Testing Go WebAssembly code on Github actions

This small post will run you through how to setup Github actions to run tests for Go code targeting WebAssembly.

OK, take me straight to the complete setup!

Here is the most basic configuration suggested by Github for Go repositories:

name: Go

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

jobs:

  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2

    - name: Set up Go
      uses: actions/setup-go@v2
      with:
        go-version: 1.17

    - name: Build
      run: go build -v ./...

    - name: Test
      run: go test -v ./...
Enter fullscreen mode Exit fullscreen mode

The first thing we need is to tell the go command we want to target WebAssembly, which can be done declaring the GOOS and GOARCH variables on the job:

jobs:

  build:
    runs-on: ubuntu-latest
    env:
      GOOS: js
      GOARCH: wasm
Enter fullscreen mode Exit fullscreen mode

The "Build" step should now work as expected, checking that our code compiles to WebAssembly.

However for the "Test" step to work, we need some more configuration.

Of course we need an execution environment for our compiled WebAssembly, in our case Node.js will be perfect, so let's set it up in addition of Go:

    - name: Set up Node.js
      uses: actions/setup-node@v2.4.0
      with:
        node-version: 14
Enter fullscreen mode Exit fullscreen mode

And finally we need to add go_js_wasm_exec to our PATH to enable go test running our tests using Node.js.

go_js_wasm_exec is located in the misc/wasm directory of the Go installation, we can add it to the PATH with a simple step:

    - name: Setup PATH for wasm
      run: echo "${{env.GOROOT}}/misc/wasm" >> $GITHUB_PATH
Enter fullscreen mode Exit fullscreen mode

Complete setup

name: Go

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

jobs:

  build:
    runs-on: ubuntu-latest
    env:
      GOOS: js
      GOARCH: wasm
    steps:
    - uses: actions/checkout@v2

    - name: Set up Go
      uses: actions/setup-go@v2
      with:
        go-version: 1.17

    - name: Setup PATH for wasm
      run: echo "${{env.GOROOT}}/misc/wasm" >> $GITHUB_PATH

    - name: Set up Node.js
      uses: actions/setup-node@v2.4.0
      with:
        node-version: 14

    - name: Build
      run: go build -v ./...

    - name: Test
      run: go test -v ./...
Enter fullscreen mode Exit fullscreen mode

This setup is based on the instructions in the Go WebAssembly wiki page, it can be adapted to run tests in a browser.

Top comments (0)