Add Jest to your CI/CD pipeline with GitHub Actions
Let’s get started
The first thing we have to do is setup our repo. We will be creating a blank project, and using vanilla javascript.
Create your Github repository
- Head over to GitHub.
- Log in to your account.
- Click the new repository button in the top-right. You’ll have an option there to initialize the repository with a README file, I usually don’t add the this file.
- Click the “Create repository” button.
Connect it to Github by following the instructions:
Adding Jest
In the root of your project directory enter in the following commands:
npm init -y
npm install --save-dev jest
Let us add some tests for a function that subtracts two numbers. First, create a subtraction.js
file
function subtraction(a, b) { return a - b;}module.exports = subtraction;
Then create a file named subtraction.test.js
. This will contain our actual test
const subtraction = require('./subtraction');test('subtracts 4 - 2 to equal 2', () => { expect(subtraction(4, 2)).toBe(2);});
Your project directory should look similar
Navigate to your package.json
file and add the following line of code:
{
"scripts":
{
"test": "jest"
}
}
Your package.json
file should look similar:
Now run npm run test
. You should receive the following output:
The next step is to create your Actions (workflow)
Github actions looks for a .github/workflow/ folder in your project directory in order for it to run actions.
- Start by navigating to the root of your project directory and running the following commands
mkdir .github/
mkdir .github/workflows/
touch .github/workflows/main.yml
This will create a .yml file inside your workflows folder. This name is optional and can be whatever you would like to name it as long as it ends with .yml
Open the main.yml and paste the code snippet below
Lets explain what each line does
name: Unit Tests
The name of your workflow. This is what Github displays on your repository’s action page
on
Required: This is the name of the GitHub event that triggers the workflow
jobs
A workflow run is made up of one or more jobs. Each job runs in an environment specified by runs-on
runs-on: ubuntu-latest
Specifies the OS you want your workflow to run on.
Steps:
Think automation here, steps just indicates the various steps you want to run on that specific job
uses: actions/checkout@v1
This is responsible for cloning the repo and checking into our project directory
run:
This tells GitHub actions to run npm install
and then run npm test
.
Lets test our workflow
Run the commands below to push your code to GitHub
git add .
git commit -m "feat: Add workflow and Jest files" -m "Testing our pipeline with jest by adding some simple test"
git push origin -u master
Navigate back to your GitHub repository and click on the actions tab
Conclusion
There you have it, a simple CI/CD pipeline with Jest using GitHub Actions
If you find this article useful, please share and clap.
Thank you