Running Angular tests with Github Actions

It is a while since Github actions were introduced, however, I got my hands on it just now. To be honest, I am really surprised how easy it was for me, a developer without any deeper knowledge of CI, to run tests for Angular CLI project, so let’s take a look.

NPM tasks

If you have generated a project with AngularCLI, you can find a bunch of tasks in package.json file.

 "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  }

First of all, let’s add a few tasks that will add production flag for the build and tests.

 "scripts": {
    ...
    "build:prod": "ng build --prod",
    "test:prod": "ng test --browsers=ChromeHeadless --watch=false --code-coverage",
  }, 

Create a new Workflow

In Continuous integration workflows category find Node.jsand click Setup this workflow.

Most likely you will not work on master, therefore we can specify that our workflow should also run for all dev branches.

 on:
  push:
    branches: [master, dev/*]
  pull_request:
    branches: [master, dev/*] 

Afterwards, I ran into the problem that npm task was unable to run because the package.json file was not located in the root folder of the repository. If you have a similar issue, add default working-directory.

 jobs:
  build:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: ng-toolkit 

Last but not least, add a few steps we want to run:

 - run: npm ci
 - run: npm run test:prod
 - run: npm run lint 

Require workflow success to merge

Since I have already used dev branches, I would also like to protect master to not be merged if the test workflow was not successful. This is actually pretty simple and you can just check an option in Settings / Branches.

Conclusion

I am pleasantly surprised how simple it was to setup a verification workflow. I cannot believe it also runs for free and this solution seems to be exactly what I needed for my personal projects.

Hope it helps you guys.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *