Jest unit and snapshot testing with TypeScript in a next.js app
Since I was asked, I will also throw Jest for testing into the stack composed of next.js and TypeScript. So let's have a look into how that can be achieved.
Add Jest
First we need to add Jest:
Next we need to update our package.json for jest configs and to also add the run script:
As you can see in the jest config, we specified an additional tsconfig file. So we create this one next:
Running the test script with npm run test lets us know, that jest cannot find any test. Makes sense, since we have not yet create one. So let us add a very simple unit test. First we create a function that we want to test:
We added a small function, that we also export so we can test it. Next we will add the jest test:
When running the test it succeeds and jest runs with TypeScript.
Snapshot testing with jest and TypeScript
At first more packages... Yay!
Next we can add a snapshot test (note that we create a tsx file this time):
Running the test shows again everything is successful. Since it was the first time we were running the snapshot test, a snapshot is created. You can find them within the newly created __snapshots__ folder.
Now let us change the Button component just a little bit. And pretend it was an accident:
Do you see the difference? No? It is hard to find... But let us run the test once again:
Now we can see there is a ! that was added. Since we really like it, we can now update the snapshot:
And run the test again with npm run test. We can see the snapshot was updated and the new testrun is successful again: