Reputation: 99
I need to implement unit tests for my Node.js API. In the API I use nothing but vanilla Node.js. Testing framework is Jest. I have tests at the moment but they all require the server to be up before running the tests (I use supertest for that).
So the question is how I can test API endpoints without actually running the server?
Upvotes: 0
Views: 1446
Reputation: 13560
So the question is how I can test API endpoints without actually running the server?
I would use nock. It is an HTTP server mocking library for Node.js.
Nock can be used to test modules that perform HTTP requests in isolation.
See the usage documentation.
const nock = require('nock')
const scope = nock('https://api.github.com')
.get('/repos/atom/atom/license')
.reply(200, {
license: {
key: 'mit',
name: 'MIT License',
spdx_id: 'MIT',
url: 'https://api.github.com/licenses/mit',
node_id: 'MDc6TGljZW5zZTEz',
},
})
Basically you create a mocking scope for a given URL and then any test that makes an HTTP request to a mocked scope will be intercepted by nock
.
You probably want to set up your mocked scopes in a beforeAll
or beforeEach
Jest block.
Upvotes: 1