我在非组件React文件中有一行代码,我需要对其进行测试,而不会被测试击中

时间:2019-02-28 16:08:42

标签: reactjs jestjs

我的目标是实现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调用中指示的行以外。我该如何进行测试?

2 个答案:

答案 0 :(得分:1)

您可以通过以下操作来测试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 :(得分:0)

您是否也在模拟和测试POST调用?也许就是这个原因。如果没有,您可以这样做:

override var description : String {
    return "SessionAccount: \(username) - \(accountType)"
}