Loading
Current section: Modules 4 exercises
Problem

Private side effects

Loading exercise

Transcript

00:00 When you use mocks in your tests, you're deviating your tested code from how it would normally behave. Different mocking techniques result in different degree of that deviation, but naturally you would want to keep it to the minimum. You wouldn't want to start testing against the code that's

00:16 completely different from what you ship in production. And mocking a module is quite a deviating technique. That is why you're almost always better off mocking particular values or behaviors. Even if it seems like those two are abstracted from you, you can still achieve full

00:32 control without resorting to module mocking. For example, if you're using a third-party request library like React Query or Axios, you don't have to mock that entire dependency to gain control over the network, over the requests that are being sent and responses that are received. Instead,

00:46 you can draw a test boundary on the network level using tools like MSW. And this way your setup is even agnostic of any particular third-party clients that you're using. That being said, there is at least one legitimate use case to use module mocking. Let's look at it. Here we have an

01:03 authorize function that's supposed to authorize a user by ID. And to do that, it uses this query table function to query this user in a database. This function itself comes from a third-party package, workshop-slash-epic-sdk. This is a made-up package, but you get the idea. And the thing is

01:19 about this package is that right in its root, it does a side effect. So on the root scope of this package, some logic is being performed. To make things worse, this logic isn't even exposed to you, the consumer. This is an internal telemetry in this case. So even if you're going to mock this

01:36 particular query table by spying on it or replacing its implementation, this telemetry logic will still run in tests. And this can result to all sorts of unpredictable behavior. In short, this is the logic that you don't want to run in tests ever. And the only way to eliminate it is to mock this

01:53 module altogether by replicating its experts, but also removing those root-level side effects. This will be the exact task you have at this exercise. So head to the authorize.test.ts and complete the test suite. Have it running at the end and see you in the solution to this exercise.