react-http-request icon indicating copy to clipboard operation
react-http-request copied to clipboard

Unable to write unit test for the component code is unreachable.

Open reeteshsingh93 opened this issue 5 years ago • 3 comments

reeteshsingh93 avatar Jun 09 '19 16:06 reeteshsingh93

In my test file:

jest.mock('react-http-request', () => ({ Request: jest.fn(() => ({ error: null, result: null, loading: true

 }))

}));

Code:

    {({ error, result, loading }) => {
      console.log(loading);
      if (loading) {
        return <div></div>;
      } else {
          console.log("i am in else");

Coverage file:

image

A HELP IS REALLY APPRECIATED..

reeteshsingh93 avatar Jun 09 '19 17:06 reeteshsingh93

i might be using wrong way to mock please correct if you believe so.

reeteshsingh93 avatar Jun 09 '19 17:06 reeteshsingh93

Hi @reeteshsingh93, it seems that there is a problem with the mock. We need to mock the default export, returning a component that calls the children prop, so you can try something like this:

import React from 'react';
import Request from 'react-http-request';
import renderer from 'react-test-renderer';

jest.mock('react-http-request', () => ({
  __esModule: true,
  default: jest.fn(({ children }) => children({
    error: null,
    result: null,
    loading: true
  }))
}));

it('should render a loader', () => {
  const tree = renderer
    .create(
      <Request
        url='https://api.github.com/users/mbasso'
        method='get'
        accept='application/json'
        verbose={true}
      >
        {
          ({error, result, loading}) => {
            if (loading) {
              return <div>loading...</div>;
            } else {
              return <div>{ JSON.stringify(result) }</div>;
            }
          }
        }
      </Request>
    )
    .toJSON();

  expect(tree).toMatchSnapshot();
});

mbasso avatar Jun 09 '19 20:06 mbasso