Loading
Current section: Network 7 exercises
lesson

Intro to Network

Loading lesson

Transcript

00:00 Mocking the network is one of the most common reasons to introduce mocking into your test suit. Well, because when you build products on the web, it often takes both the client and the server for those products to do something.

00:12 And naturally, you would want to gain control over the network, over the communication, so you're able to test your client-side code reliably. Well, but why? Why do you have to intercept requests and mock responses? Well, imagine you have a React component that fetches the user.

00:29 Sure, making that request is a part of that component, so it's important. But it's not the only part, and it's not the main intention here. The intention behind that component may be to render some UI based on the user state, for example. So that is the thing that you need to test in the integration test for that component.

00:47 But if you leave that request as is, and it will be able to run, it will hit the actual server during the test run. So suddenly, you're testing both your client and your server, although implicitly. The runtime of your server is now fully capable of affecting the results of your test.

01:03 And that's a bad thing to have, because it violates the golden rule of assertion. Basically, even if your React component works perfectly, the test may be crashing because the server is down or having a hiccup. And that is not the kind of test you want to write. Historically, there's been a lot of ways to intercept requests in JavaScript.

01:20 And a lot of them came down to mocking the request client. For example, the fetch function or axios.get that you're using in the code that you're testing. But the thing with those approach is it deviates your tested code a bit too much. See, when you mock the request client, you're actually throwing away the entire logic that it has.

01:39 Things like request validation, or maybe serialization and normalization of the payloads you're sending, but also the underlying network code in Node.js. And that is not what you want to do, because if you deviate your tested system too much, well, you'll be testing a completely different system.

01:55 This is why in this workshop block, we will be using a library called MockServiceWorker. MSW is a bit different when it comes to intercepting requests, and it's created its unique algorithm, so when you run MSW, it affects your environment and your request clients as little as possible.

02:11 You're going to love working with MSW, and I think it's time you finally explored it.