首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我需要测试的非组件React文件中有一行代码不会被测试命中

我需要测试的非组件React文件中有一行代码不会被测试命中
EN

Stack Overflow用户
提问于 2019-03-01 00:08:42
回答 2查看 47关注 0票数 1

我的目标是100%的测试覆盖率,我有一个名为agent.js的文件,它包含:

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调用中指出了这一行。我怎样才能得到测试呢?

EN

回答 2

Stack Overflow用户

发布于 2019-03-01 08:53:48

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

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
})
票数 1
EN

Stack Overflow用户

发布于 2019-03-01 01:27:34

你也在模拟和测试POST调用吗?也许这就是为什么。如果没有,你可以这样做:

 /* istanbul ignore next */
 }).then(res => res.json())
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54929843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档