0

I am trying to write a test case for a functional component which uses hooks for state update and gets data from a mock promise call.

// Functional Component

const MockPage = () => {
  const [mockData, setMockData] = React.useState<IMock[]>([]);
  const mockService = new mockService();

  React.useEffect(() => {
    mockService.getMockData().then((res) => {
      setMockData(res);
    });
  }, []);

  return (
    <div>
      <MockTable mocktData={mockData} />
    </div>
  );
}

Here is the test case that I have written which PASSES :

 it('renders without crashing', () => {
        mount(<MockPage />);
    });

Here are the test cases that I have written which FAILS :

 it('renders without crashing', () => {
       const wrapper =  mount(<MockPage />);
        expect(wrapper.is(MountTable)).toBeDefined();
    });



it('renders without crashing', () => {
           const wrapper =  mount(<MockPage />);
            expect(wrapper.find(MountTable).prop('mockData').toHaveLenght(2);
        }); // assusming the mockData has 2 objects in an array

What is the mistake(s) am committing here? Is there something am missing?

Note: I tried doing with act() too , but was not successful.

2
  • You could use debug to see what's actually getting rendered: console.log('wrapper', wrapper.debug()); Also on the last test you're missing a parenthesis before .toHaveLenght(2). Commented Aug 20, 2019 at 12:03
  • @Clarity I did that but it says an empty Renderer object Commented Aug 20, 2019 at 14:18

1 Answer 1

1

Your data fetching happens asynchronously, so you need to wait for the promise to resolve before checking your data.

At a minimum (although this won’t always work when you have multiple promises), you can do this:

const wrapper = mount(<MockPage />);

return Promise.resolve().then(() => {
  expect(...).toBe(true);
});

There’s a great library called wait-for-expect that can also help when return Promise.resolve().then(...) isn’t enough:

import waitForExpect from `wait-for-expect`;

const wrapper = mount(<MockPage />);

return waitForExpect(() => {
  expect(...).toBe(true);
});
Sign up to request clarification or add additional context in comments.

2 Comments

It fails with the following error expect(received).toBe(expected) // Object.is equality Expected: true Received: false
That’s not enough information to help debug this. What is received/expected? If those are objects or arrays you will need to use toEqual instead of toBe . You can use your toHaveLength check if that’s simpler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.