Skip to content

Latest commit

 

History

History
58 lines (34 loc) · 3.4 KB

File metadata and controls

58 lines (34 loc) · 3.4 KB

Testing Web Services

In this section, we are going to learn how to test web services built with Express.

What should we test

In a web service implemented using Express framework, there are the following components:

  • route handlers
  • middlewares
  • models

We can write unit tests for each of those components. However, there are some challenges we need to address when writing unit tests:

  • The models usually have a dependency on some database API (e.g. Mongoose). How do we handle that dependency during testing?
  • The route handlers or middlewares usually have dependencies on the models (and some of them may have dependency on other web services). How can we handle those dependencies?

We should also write tests to verify our API endpoints work as we designed (e.g. sending requests to those API endpoints and verify the responses are the same as expected.) This kind of tests can be considered as Contract Tests because they check if the APIs work according to the contract agreed with the API consumers. They can also be considered as Integration Test because we usually test all the components (route handlers, middlewares, models, and even databases) as a whole and see if they work correctly together.

References

Here are more articles talking about different ways to testing Express based web APIs. They may have different opinions regarding on the unit test vs integration test. There is no absolute right or wrong answer.

Unit Testing Express Middleware

Unit Testing Data Models

Unit Test Express Routes

Integration Testing with real database

Integration Testing with a mock database

Test Express API with Jest and Supertest

Misc References

A workshop for learning how to test JavaScript applications