Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
reeteshsingh93 opened this issue Jun 9, 2019 · 3 comments

Comments

@reeteshsingh93
Copy link

No description provided.

@reeteshsingh93
Copy link
Author

reeteshsingh93 commented Jun 9, 2019

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
Copy link
Author

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

@mbasso
Copy link
Owner

mbasso commented Jun 9, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants