Check out a free preview of the full Enterprise UI Development: Testing & Code Quality course

The "Mocking API Requests" Lesson is part of the full, Enterprise UI Development: Testing & Code Quality course featured in this preview video. Here's what you'd learn in this lesson:

Steve introduces the Mock Service Worker library, which allows developers to mock API requests by intercepting requests on the network level with a service worker. The mock definitions can be seamlessly reused for testing, development, and debugging.


Transcript from the "Mocking API Requests" Lesson

>> So I argued if you were back end engineer, you would have a lot more of a grace from me to mock stuff out, right? Systems, writing to the database, maybe don't choose to do it, credit cards awesome, right? Like all sorts of stuff that you shouldn't do.

Front end engineers, it's like time, random UUIDs, Random sorting, And then the last one, which I keep skirting around is API requests. So the meta point that I was trying to build to is on a periphery, the best practice for a really long time, and if you still do it, you have no judgment from me, is mocking out fetch.

XAHR callback, wow, I don't remember HCG. I don't even remember what the old event was that fetches based on two big ajax requests before fat. That's, that's the sign the times are changing XML HTTP request. There it is, objects, whatever. You could do all of those things, the thing is mobile phones exist and one of the things that exist on mobile phones these days are progressive web apps with offline mode.

And those are powered by service workers. Service workers exist behind the scenes and they run outside the browser context. Their main job is they intercept network request so that you can have stuff like offline mode and stuff like that. And then instead of going and hitting the network, you can check the cache API, right?

Or read from indexedDB and respond to network requests without calling out to the network. You can intercept network requests from outside of your app and respond to them without hitting the network. So could you mock and stub out fetch or Axios or what have you, but that's now code you're not covering, right?

Cuz you mocked it out and replaced it, which means that code coverage tool is never hitting those things, right? It would be really cool if we could get all the way to the edge of what we control, which is basically outside of our browser context, right? And then intercept it, and this is a library that is really exciting.

And the one of the reasons I wanna call it out is test, yeah, sure, sure, sure. I aspire every company I work out that I should be able to develop on an airplane. Which means in a perfect world, my environment should be set up in such a way that I don't need a network connection to work on my thing.

There's some jokes about the amount I need to npm install to get my job done, but that's not important. But one of the things that you can do nowadays, if you look at this given code example right here, for mock service worker, it looks almost like an express app if you squint, right?

It's basically you can just write a layer that fakes out your API. The various ways I've done this over time, which is one, just spinning up an express server that you actually talk to. And just having an environment variable go into local host, whatever port versus like something else.

There's different ways that people have done this in the past. This is really great, it sets up a service worker in the context. And what's really great about it is you can use it in your tests to simulate the network, do you know where else you can use it?

In development, and so this now goes back away from testing and more back to our core enterprise app stuff, right? Occasionally, I don't know if this ever happened any you all. You need to work on something before the API is ready. And maybe there's a deadline and the backend team says we're totally gonna have the API done three months before that deadline?

Has that ever happened to anyone where they actually got it done on time? No, no, software engineers don't make good guesses backend or frontend, right? We were sandbagging when we said three months, we thought we could do two, it took us four, and it took them four, right?

We had a four-month window to begin with. So what's really great about this is that you can, just for the API that you need to, like you don't have to, it's not an all or nothing thing. It will intercept anything, to, in this case, in this example, we have on page a post on a REST API to /login.

And then you can control it and do the response. I think a question one of you asked me earlier, right? When is it okay? This is like, we're still sending out the network requests as far as the browser is concerned, right? It's just somebody's catching it right outside and handing it back to us.

So you can do all your APIs, you can do just a few of them, right? You can also have it if you like want it to blow up. If it's an unhandled request, you can set that as well. But you can either a in your tests, start up one of these like mock service workers to basically pretend to be a server.

So you're not patching, you're not monkey patching, fetch. You're not doing any of those things. Basically your code is running as it would in the browser. There's just something like outside. It's like we didn't feel bad when we use JS Dom, did we? I mean, maybe you did, I don't know, I didn't feel bad, right?

And the same is true here, where your code is running the same way it will in production, right? And your tests are actually like, your mocking is happening outside of what you control in the truest sense, and it's super powerful. But also I am doing it like a specialized sales pitch for this test.

Yeah, sure, sure, sure. Great for development, for APIs that are not done yet, for all sorts of different things, or even simulating stuff that you need to simulate in a certain way. A lot of times you might get a bug report. And like you can't get the server to do that thing.

And so you're using the app to try to get like staging into some weird condition where you can recreate it here, you can literally take the API response, have it be the thing, right? Just use it kind of in development as well. Especially in a large application, there's tons of things you do not control, there are services you don't own.

And so this allows you to put them in various states and simulate a network, could you spin up your own development server? You could, but now that's the thing that you gotta spin up next to it. This is basically you can do, if process.nodeenv = development, spin up the service worker, right?

Or have something where you don't have it running, or something along those lines. You can have pieces of your code, depending on where they're running. Just basically use this and then your code is running the true way that it would normally run, which will give you a lot more confidence.

So again, some of these things like around mocking stubbing are worthy of more than we have our time and attention for and are distracting from the meta point that we're trying to do. Which is how do you kind of put the metal suit armor around the planet and not unleash Ultron there, I made the Marvel reference.

We can close this section out with that. I made it all the way to the end. How do you put this around your app so that you can begin doing these important refactors? I think this is a really great way to do that, right? You can simulate these things, but not actually put a lot of conditional logic in your code.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now