#Unit testing loaders

1 messages · Page 1 of 1 (latest)

quick lily
#

Hi all! I'm new to the concept of unit testing on web development.

I have loaders/actions defined all throughout my web app that call 3rd party APIs. What is the best practice to unit test these kind of loaders? Would I re-create them as mock resource routes and swap the calls out for mock API's instead? Or add parameters to go down a different path in the code execution to mock the API data rather than make a fetch call.

Any help would be appreciated, thank you!

heavy rune
#

My first tactic is always to avoid mocking if possible. Can you extract the logic you want to test into a function that can be tested on its own? If you really need to assert on the return of the loader itself, then you'll want to mock out the API calls.

quick lily
#

Yeah I suppose in theory I could start extracting hte code out of my loaders/actions but now I'd have to rethink how I structure my codebase. If I'm understanding it right, the functions should take in the data to act on & teh loaders/actions just handle the actual fetch calls. This way when I'm testing I can just call the functions with the right params as you would to make sure it matches the output I want

heavy rune
#

yeah, basically that's it, same as testing code in any other context. If the thing you want to test has too many internal dependencies, either find a way to inject them (not really possibly with actions and loaders) or break the implementation into smaller pieces that are more easily tested. FWIW, the Remix folks suggest that testing your real loaders/actions is better served by E2E testing rather than unit testing. My experience is that's absolutely true when you start dealing with auth/cookies/session/redirects/etc. All these things are hard to set up in a unit test.