How to create GitHub workflow to run unit test case in Node.js
GitHub workflows are a powerful way to automate your software development process, including running unit tests for your Node.js application. In this blog, we’ll walk through how to create a simple GitHub workflow that runs your unit tests every time you push code to your repository.
Step 1: Set up your Node.js project
Before we can create a workflow, we need to have a Node.js project with unit tests. If you don’t have a project already, you can create a simple one with the following steps:
- Create a new directory for your project and navigate to it in your terminal.
npm initto create a new
package.jsonfile for your project.
- Install your testing framework of choice (e.g. Jest, Mocha, etc.) and any necessary dependencies using
Once you have your project set up and your tests written, you’re ready to create a GitHub workflow.
Step 2: Create a new workflow file
In your repository, create a new directory called
.github/workflows. Inside this directory, create a new file called
test.yml. This will be the file that defines our workflow.
Step 3: Define the workflow
test.yml, add the following code:
name: Node.js CI on: push: branches: [ main ] jobs: build-and-test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Use Node.js 14.x uses: actions/setup-node@v2 with: node-version: '14.x' - name: Install dependencies run: npm install - name: Run tests run: npm test
This workflow does the following:
- It runs on every push to the
- It defines a single job called
- It runs on the
- It checks out the code from the repository using
- It sets up Node.js 14.x using
- It installs dependencies using
- It runs tests using
Step 4: Commit and push
Once you’ve added the workflow file, commit your changes and push them to your repository. GitHub will automatically detect the new workflow and begin running it every time you push code to your repository.
Step 5: Check the results
You can view the results of your workflow by going to the “Actions” tab in your repository. Here you’ll see a list of all the workflows that have run, along with their status (success, failure, etc.). Clicking on a workflow will show you the details of each step, including any output generated by your unit tests.
And that’s it! You now have a GitHub workflow set up to automatically run your unit tests every time you push code to your repository. You can customize this workflow to meet your specific needs, such as adding additional steps or running the workflow on different branches.