我有一个非组件一行代码阵营文件我需要测试的是没有得到通过试验击中(I have a line of

2019-09-29 01:28发布

我的目标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
}

我有一个覆盖除了我在取呼叫表示样样在行测试。 我怎样才能像测试?

Answer 1:

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

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


Answer 2:

你是否嘲笑,太测试POST调用? 也许这就是为什么。 如果没有,你可以这样做:

 /* istanbul ignore next */
 }).then(res => res.json())


文章来源: I have a line of code in a non-component React file I need tested that doesn't get hit by tests