DEV Community

Thanh Tien Phat Nguyen
Thanh Tien Phat Nguyen

Posted on

Unit testing your code!

Introduction

This week, we embarked on how to create a testing units and workflow using Github Actions. The testing framework I choose is "Jest" because of its popularity and simplicity for using.

How to integrate "Jest"

  • Firstly, we need to install by using
npm install --save-dev jest

Enter fullscreen mode Exit fullscreen mode

In package.json, add the following lines:

{
  "scripts": {
    "test": "jest"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • We can create the first test file by using this naming convention checkFunctions.test.js
  • We can easily run the test by using:
npm run test
Enter fullscreen mode Exit fullscreen mode

What did I learn while writing my test case:

Well, since my test case is pretty long. Thus, I highly recommend you to have a look at my test file.

  • I have learned how to write a test unit that we can compare right from console.log
  • I have learned to consider many options that could happen for my functions

Add Continuous Integration

  • Github Actions is a CI that is highly recommended. Therefore, I would like to introduce a bit about the way we set it up.
  • Firstly, we need to create a template to the .github/workflows directory of your repository.

  • This is how the YML file looks like:

name: Node.js CI

on: [push]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [8.x, 10.x, 12.x]

    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v1
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm install
    - run: npm run build --if-present
    - run: npm test
      env:
        CI: true
Enter fullscreen mode Exit fullscreen mode
  • A CI is perfect when we want to automating all our test in a large project. However, if someone's change might break the tests, there's no way we could merge them until their changes are fixed. This way help us to save tons of resource.

Learning from the process:

Well, this week assignment is highly educational. There are several things I could learn from the lab:

  • How to set up a CI
  • How to write a simple unit test
  • How to set up a code coverage analysis so that I could write more test to cover the aspects that I might miss of a function.
  • How to fix my functions when there are bugs while testing.

Top comments (0)