Test get request in javascript

你。 提交于 2020-11-29 03:52:34

问题


I have the next get request:

const getReq = () => {
  fetch(
    'https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits',
  )
    .then((response) => {
      let status = null;
      if (response.status === 200) {
        status = response.status;
      } else {
        status = 'error';
      }
      if (status === 200) {
          alert('success')
      } else {
          alert('Error')
      }
      return response.json();
    })
    .then((commits) =>{
        return commits.map(i=> i.sha[0])
    });
};
getReq()

I want to make 3 tests for this request:

  1. if I get the first sha from commits: i=> i.sha[0]
  2. check for the 200 response
  3. check for the response that is not 200.

I wrote my first test:

import { getReq } from './getReq';

global.fetch = jest.fn(() => {
  return Promise.resolve(123);
});
describe('success', () => {
  test('get first sha http', async () => {
    const sha = await getReq();
    expect(sha).toBe(123);
  });
});

But I get TypeError: Cannot read property 'then' of undefined.

How to solve the issue with the test above?


回答1:


Your promise is not getting mock. You can try to adding this on the top of the file.

jest.mock(path_of_getReq_file, () => ({
  getReq: jest.fn()
}));


来源:https://stackoverflow.com/questions/65037208/test-get-request-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!