We are going to be using the very simple TypeScript API we developed in a previous tutorial in order to learn about Jest Testing.
In this tutorial, we’ll be looking at how you can get a very simple test framework up and running for your TypesScript based API using the
supertest testing libraries.
Now that we have gotten the
why? out of the way, let’s see how we can go about implementing our own testing framework:
First and foremost, we’ll have to install the libraries that we wish to use to test our systems.
Once you have installed the above packages, you will have to add the
test script to your
package.json file within your project:
You’ll notice we’ve also added in the
jest configuration to our
package.json in the above code snippet. This dictates where
jest will be able to find our tests and in this case we’ve dictated they’ll be within our
A Simple Test
Ok, so we’ve got the necessary libraries installed, how do we then go about using these to test our codebase?
Well, let’s start by writing a really simple
jest test suite that will test a very simple
hello API endpoint.
In the above test suite we have used the
supertest library to make a test request against our API endpoint
GET "/". This then awaits the response and tests this response to ensure it’s what we expect.
Running our Tests
Now that we’ve got this test case written, let’s try running our test suite by calling the following:
This should then return the following output:
Excellent, we now have a running, incredibly simple testing framework that we can start to flesh out and use to test every other endpoint or function within our TypeScript based REST API.
I hope you enjoyed this tutorial! If you found it useful and wish to learn more then please feel free to follow me on Twitter where I actively post new stuff: @Elliot_f.