Getting started with Jest
Let's start by testing a small sum function and check that it correctly sums two numbers.
The first step would be, of course, to install Jest:
npm install jest
Create a directory test
and add a file called sum.js
with the following content:
// test/sum.js export default function sum (a, b) { return a + b }
Now add a test spec file for this function:
// sum.spec.js import sum from './sum' describe('sum', () => { it('create sum of 2 numbers', () => { expect(sum(15, 8)).toBe(23) }) })
We need a command to run tests. Add an entry "test"
to the package.json
file that will call a command jest
:
// package.json
"scripts": {
//...
"test": "jest"
}
Now if you run npm test
, you will see some errors:
This happens because our Jest is not aware we are using ES6! So, we need to add the babel-jest
dependency:
npm install babel-jest --save-dev
After babel-jest is installed, we have to add a .babelrc
file with...