Depending on your test framework, you may need to use external libraries for certain operations e.g. mocking, replacing require
d modules with fake ones, intercepting HTTP requests, and so on if your test framework does not include support for those, or if you need to do something more advanced.
When you write unit tests, often you need to mock out some of the dependencies. The following tools may be useful for this purpose:
-
sinon: a popular dedicated library for mocks and stubs
that can be used with Jest or other test frameworks
- fetch-mock: allows mocking http requests made using fetch
- nock: test modules that perform HTTP requests in isolation
- sinon-mongoose: mocking Mongoose model objects
- mongoose-mock
- mockgoose
- Faker.js: generate massive amounts of fake data in the browser and node.js
When you test with a real database, usually you need to populate the database with some data to meet the pre-condition for running your tests.
The following libraries help to create fixtures:
But sometimes it's not difficult to load data to database just using the save()
API provided by Mongoose.
If you are using MongoDB, the following libraries help you to create a dedicated MongoDB instance just for your tests. Then you have full control on the data in the database, and you can throw away the database after running the test.
To verify your API works as expected, usually you need to send some requests to a running instance of your application, and check the responses.
This can be done manually using tools like postman or insomnia, but we prefer to automate those tests.
To automate those tests, the tests need to act as API consumers, issuing requests and verify responses. For this purpose, you can use library like supertest.