If you’ve never written a test before or usually turned off by the complexities of setting up and having to write verbose tests, Jest may be up your alley.
Getting started with Jest
Installing Jest to a new or existing project is easy. Simply install it with NPM and then…
…add these two scripts to your
You can run your tests with
npm run test or have Jest watch for changes in
your code and run the tests with each change using
npm run test:watch.
But before we get ahead of ourselves, we need to actually write a test for Jest to test against.
Writing your first Jest test
For Jest to run your tests, they need to live inside a
(this doesn’t have to be at root level and you can have more than one too) or your
files need to end in
Here I define and export a function called
sum, it takes two arguments and
adds them together.
And here’s the test. Fairly straight forward looking right? We define a test, tell Jest what function to run and what we expect the outcome to be.
Note in the above example I’m importing my
sum function but where are
expect coming from? These are in the global namespace when the tests are run
Now if you run
npm run test you shall see Jest’s rather nice output.
At a basic level, that’s all there is to it. Of course there are other types of tests and the like but this should be enough to get you going.
If you’ve taken a likening to Jest you can read up on the it on the official website.
Writing more than one test?
Well fear not, Jest still has the common
it blocks that you may
see in other frameworks that help separate out your tests.