Testing express routes with JEST
12,293
The problem is you are not mocking the request
module that you are importing.
See https://jestjs.io/docs/en/tutorial-async for details on mocking.
Author by
Aw3 Sol
Updated on July 01, 2022Comments
-
Aw3 Sol almost 2 years
I wanted to test my express API endpoints with JEST.
Below is my Express API code.
routs.ts
// Get release notes routes.get('/release-notes', (req, res) => { request.get({ url: 'https://host.com/rest/api/content/search?cql=parent=209266565', json: true }) .pipe(res); }); export default routes;
Above code will return the data but I want to test the API, with Mock without making an API request
So I have manually created a mock response and need to verify the code with it.
Mock.ts
export const releaseNotesMockData = { 'results': [ { 'id': '206169942', 'type': 'page', 'status': 'current', 'title': 'Release 2018-10-18 Full Flow CM00294965', }] };
With the below code, I hit the real API and the test passes
describe('Test a 200', () => { test('It should respond with a 200 status', async () => { const response = await request(app).get('/release-notes'); expect(response.statusCode).toBe(200); }); });
Issue is, I do not want to hit the real API for testing instead I want to use the Mocks for testing.
Below is code which I tried and it did not work. Please help
routs.test.ts
describe('api test', () => { const url = '/release-notes'; it('user GET should be 200', async () => { const result = await http({ url, method: 'get' }); expect(result).toBe('200'); }); });