docs
Local Development
Test with Jest

Testing with Jest

We now have our backend and database up and running locally in a container. This means we can build our APIs and test them!

As you've seen earlier, we are using Jest for testing. With Jest, we can perform unit tests, integration tests, and much more. I've added a sample test script called endpoints.test.ts to get started.

The test script covers two endpoints:

  • The root / endpoint
  • The /users endpoint

Let's open up another terminal.

Create Permission Set

💡 Make sure the backend (npm run docker:compose) is running in another terminal, as shown in the image above.

Run our test command on a new terminal:

npm run docker:compose-test

This will execute all the test scripts located in the tests folder.

After a moment, you’ll see the test results:

  • 1 test passed
  • 1 test failed

Why did one fail? This is because the /users endpoint now has seeded data, so the response isn't a 404 anymore. Let's go ahead and update the /tests/endpoints.test.ts to reflect this change.

Update the httpStatus to OK.

Create Permission Set

Now, rerun the test:

npm run docker:compose-test

Great! Now both tests have passed! 🎉

Running Tests in Watch Mode

One of the best parts of using Jest is the ability to run tests automatically as you make changes to your API. To do this, we can attach the -watch flag so tests are executed in real-time whenever we update the code.

Run the following command:

npm run docker:compose-test:watch

Now, let's switch back to a scenario where the /users endpoint returns a 404 response. Watch mode will automatically detect this change and rerun our test scripts.