测试使用javascript获取请求 [英] Test get request in javascript

查看:33
本文介绍了测试使用javascript获取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个获取请求:

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()

我要为此请求进行3个测试:

I want to make 3 tests for this request:

  1. 如果我从提交中得到第一个sha:i=> i.sha[0]
  2. 检查200个响应
  3. 检查响应是否为200.
  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);
  });
});

但是我得到了TypeError: Cannot read property 'then' of undefined.

如何通过上述测试解决问题?

How to solve the issue with the test above?

推荐答案

您的诺言没有被嘲笑. 您可以尝试将其添加到文件顶部.

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

这篇关于测试使用javascript获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆