Skip to content
This repository has been archived by the owner on Jun 2, 2023. It is now read-only.

UseEffect hook and testing-library #839

Open
wynsoft opened this issue Sep 9, 2020 · 4 comments
Open

UseEffect hook and testing-library #839

wynsoft opened this issue Sep 9, 2020 · 4 comments

Comments

@wynsoft
Copy link

wynsoft commented Sep 9, 2020

Hi Kent,

Sorry to bother you but I have a component that has a few useEffect hooks. Each of them is responsible to do a single task. One reads the params from the URL as stores it in state using the useState hook. The second useEffect checks if the params from the URL are set in state and then makes an API call to fetch some data. I want to be able to test the API call from the second useEffect and check if it has been called and with what it has been called with. When the API succeeds it calls a function that dispatches updates to the context. I would like to test this call to this function and also the dispatched within it.

Is this possible to do with the testing-library? If so, your guidance on how to achieve this will be highly appreciated.

Thanks,

Derrick.

@kentcdodds
Copy link
Owner

Hi @wynsoft,

I'm afraid this is difficult to answer without code, however to talk in general terms, consider how your users will trigger this code to run and try to make your test do the same thing :)

@wynsoft
Copy link
Author

wynsoft commented Sep 14, 2020

Hi @kentcdodds,

Thanks for answering. I understand it's hard to figure out without code but I can't share the code as the company I work for won't permit it. Anyway, I did write tests to cover how the user would trigger it but the Jest coverage report shows that the API calls within the useEffect are not covered. My company insists that this needs to be covered but the tests written so far do cover what the user experiences on the outcome of these API calls. My dilemma is when using testing-library should be testing the actual implementation of the code. Any way, I did find a way to test this code out but I'm still not sure it that's the type of tests we should be writing using the testing-library. I would have thought those type of tests should be covered using Enzyme.

@kentcdodds
Copy link
Owner

Yeah, you definitely don't want to be using enzyme at all.

Maybe the issue is in how you're mocking the API calls? Maybe this can help? https://kentcdodds.com/blog/stop-mocking-fetch

@wynsoft
Copy link
Author

wynsoft commented Sep 14, 2020

Thanks. I'll surely take a look at your suggestion. :)

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

No branches or pull requests

2 participants