我在非组件React文件中有一行代码,我需要对其进行测试,而不会被测试击中 [英] I have a line of code in a non-component React file I need tested that doesn't get hit by tests

查看:141
本文介绍了我在非组件React文件中有一行代码,我需要对其进行测试,而不会被测试击中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是100%覆盖测试,并且我有一个名为agent.js的文件,该文件具有:

I'm aiming for 100% test coverage, and I have a file called agent.js which has:

export const requests = {
    get: url => fetch(url).then(res => res.json()),
    post: (url, body) =>
        fetch(url, {
            method: 'POST',
            body: body,
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(res => res.json()) //**this line lacks coverage**
}

export const Gatherings = {
    getAll: () =>
        requests.get(API_ROOT + '/gatherings'),
    postAll: () =>
        requests.post(API_ROOT + '/gatherings')
}
export default {
    Gatherings
}

我有涵盖所有内容的测试,除了我在fetch调用中指示的行以外.我该如何进行测试?

I have tests that cover everything except the line I've indicated in the fetch call. How can I get that tested?

推荐答案

您可以通过执行以下操作来测试并获得requests.post的100%代码覆盖率:

You can test and get 100% code coverage for requests.post by doing the following:

import { requests } from './agent';

test('requests.post', async () => {  // use an async test function
  const realFetch = global.fetch;  // save the real fetch
  const spy = jest.fn();
  global.fetch = jest.fn(() => Promise.resolve({ json: spy }));  // mock fetch
  await requests.post('the url', 'the body');  // wait for the Promise to resolve
  expect(global.fetch).toHaveBeenCalledWith('the url', {
    method: 'POST',
    body: 'the body',
    headers: {
      'Content-Type': 'application/json'
    }
  });  // SUCCESS
  expect(spy).toHaveBeenCalled();  // SUCCESS
  global.fetch = realFetch;  // restore the real fetch
})

这篇关于我在非组件React文件中有一行代码,我需要对其进行测试,而不会被测试击中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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