简体   繁体   中英

Testing express routes with JEST

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');
  });
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM