Writing a test

Writing our first test - you can see the full code here: https://github.com/mmagnusen/calculator

This is an example of a test:

example-test.spec.js
1
describe('calculatethearea',()=>{
2
3
constcalculateArea=(length,width)=>{
4
returnlength*width;
5
}
6
7
constarea=calculateArea(2,2);
8
9
expect(area).toBe(4);
10
11
})
12

What is happening here?

describe() is a method. It accepts two parameters. The first parameter is a short description of the test. We have written our description as calculate the area

The second parameter is a function, which will be called by Jest. Inside this function, we can outline what we want to test to do and say what we expect the result to be.

First we created a function, called calculateArea. It will be passed a length and a width and should return the length * width to calculate the total area.

We now call that function, passing it a length of 2 and a width of 2. We assign the result of this function call to a constant named area.

expect() is a function, which should be passed a value. This can be any type of value, in our case it is a number.

expect() will always be used with a matcher, which lets you validate what the value should be. We can say things like we expect the value to be something, to equal something, to be a certain data type etc. We are saying we expect the value areato be 4.

Where should we place our tests?

Jest can find

  • any file with a `.test.js` or `.spec.js` suffix
  • any `.js` file within a `__tests__` folder

Running our test

Navigate to the root of your project and type in the following command:

npm run test
  • This command runs tests in 'watch mode' - this means any changes made to a component will re-run tests associated with that component
  • can find any file with a `.test.js` or `.spec.js` suffix
  • jest can find any `.js` file within a `__tests__` folder

The result of our test

console screenshot

Here, Jest is showing us the result of the test we have written.

We are given information such as whether the test passed or failed, which file the test was in, how many total tests were run and how long the tests took to run.