0

I have a React component that doesn't render until fetchUser status is not loading. My test fails because the component is not rendered the first time and therefore can not find page loaded text. How can I mock my const [fetchStatusLoading, setFetchStatusLoading] = useState(false) on my test so that the page would get rendered instead of loading text?

const fetchUser = useSelector((state) => (state.fetchUser));

const [fetchStatusLoading, setFetchStatusLoading] = useState(true);

useEffect(() => {
   setFetchStatusLoading(fetchUser .status === 'loading');
}, [fetchStatusLoading, fetch.status]);

useEffect(() => {
        // this is a redux thunk dispatch that sets fetch.status to loading/succeeded 
        dispatch(fetchAPI({ username })); 
}, []);

if(fetchStatusLoading) return 'loading..'; 
return (<>page loaded</>) 

// test case fails 

  expect(getByText('page loaded')).toBeInTheDocument();
1
  • 1
    Have you tried wrapping your expect in a waitFor block? Commented Mar 26, 2021 at 13:40

1 Answer 1

1

If you were able to mock the loading state you would only be testing the code on the "render" part and not all the component logic you are supposed to test, as this is the way Testing Library means to shine.

If this is just an asynchronous problem, you could do something like:

test('test page loaded', async () => {
  render(<MyComponent />);

  expect(await screen.findByText('page loaded')).toBeInTheDocument();
});

But it seems that your component contains an API request, so if the component accepts a function you could mock it and return the value, or you could mock fetch. Here are some reasons why you should not do that.

Using nock or mock-service-worker you can have a fake server that responds to your API requests and therefore run your component test without having to mock any internal state.

Testing Library just renders the component in a browser-like environment and does not provide an API to modify any of the props or the state. It was created with this purpose, as opposite of Enzyme, which provides an API to access the component props and state.

Check out this similar question: check state of a component using react testing library

Sign up to request clarification or add additional context in comments.

Comments

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.