Mocking APIs During Development in React

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey how's it going everyone it's lee halliday and today we are going to learn about mocking our apis in the development environment and we're going to do that with mock service worker now i've done another video showing how to use mock service worker with testing but we're not testing this time we're just we're doing development and maybe we don't have our api endpoints ready yet maybe there's another team working on them so we can use this to basically fake them out and not let it hold us back developing our front end so what we're going to do is basically get started by creating a brand new next.js application so i'm in my console and i'm just going to say yarn create next app and we'll call this msw mocked api so we'll just wait for this to install and then we'll install the packages that we need okay so with next installed we're going to go into that folder and then we're going to add two packages so we're going to be adding mock service worker which is msw and also swr stale while revalidate to basically help us make those api requests on the front end in the client so we're going to install that okay so once msw and sw are installed we need to initialize mock service worker and this tripped me up a little bit because i didn't see it in some of the examples but we can do that using npx mwmsw init so many acronyms mess me up so when we try this it's going to ask like basically where do you want us to initialize the folders or the files that it needs so we're going to do that in public because that's where sort of all of this static stuff goes inside of next.js so if we were to open up our code base right now i'll just show you what has been created so in our package.json we've got msw installed we got stalewell validate installed and there's some msw set up here that says basically where is the service worker going to be installed in the public folder so if you were to go inside of public here you see this file mock service worker it needs this and you're going to get an error if it can't find this it's basically the code that installs the service worker in whatever environment you're working in but you never need to touch this file it's just needed for this to work properly so we're going to go inside of pages inside of index and we're just going to rip everything out so you can just do this and maybe we just want to put a ul for now that's it if you want you can put 1li but it will be empty and then you can delete everything else here so our goal on the home page is to basically list some coins some some crypto tokens some symbols so what we're going to do is basically make a request using swr to an endpoint that we're going to eventually mock out to get a list of these coins to display so for that we're going to import use swr from swr and then what we're going to do inside of our component here is we're going to say const data and an error is equal to use swr and with that you need to give it uh some sort of key so that it knows sort of uh one request to from another one so we're just going to call this coins and then you have to pass it a function to basically go and load that data so we're going to create one called get coins so we can do this here we can say function get coins and we need to return and we're going to make a fetch call to slash coins and then the response will give us the json and that's pretty much all we need to do here and then we come down and we basically handle when it's in an error state and when it's loading so we'll say if there's an error we're going to return just a span that says error and if there's no data we'll return a span that says loading and if we get down here at this point we can sort of assume that it worked and why don't we just for that why don't we json.stringify the data inside of this li like that so that we can see what we're working with so let's start our app and we'll say yarndev to get this up and running and we'll go to the browser here so if i were to refresh the page what we're going to see as soon as this thing sort of initializes is we get an error so why do we have an error because this endpoint doesn't exist so if we were to just oh boy get rid of this look at our coins so it's a 404 so it can't find this thing so now we're going to go and we're basically going to create a fake version of this endpoint using mock service worker hey i just wanted to mention my course next level next gs which you can pick up from next.leehalliday.com if you want to show your support to this channel or you want to learn some new techniques with nexjs where we build a full stack application covering the front end and the back end covering graphql typescript prisma using maps it's a whole lot of different technologies in eight plus hours of content 29 videos you can pick it up for 49 us dollars or click this purchasing power parity to get a bit cheaper price depending where you're from please check it out thanks so much service worker needs to be sort of initialized in a central place so yes we could put it here in this index file but then it would only be available on that page so i'm going to do this inside of the underscore app file which is global on next.js it's sort of something that's called and is wrapped around every page so in here what we're going to do is we're going to um require dot dot slash mox like this so this folder doesn't exist yet we're gonna go create it in a second but i don't wanna always use the mocks because in production for example i don't wanna use them maybe locally even i don't want to always use them maybe sometimes i want to use the real endpoints so what we can do here is we're just going to check to see if the value of an environment variable is equal to enabled so we're going to say if process dot end dot next public api mocking is equal to enabled we're only going to require the mox if that's the case and that's why i did sort of a dynamic require rather than importing it at the top because i only sort of want to conditionally go and import this code here so we obviously need to set up this environment variable i'm going to do that in development which will only be loaded in the development environment and i'm going to say that this is equal to enabled so whenever you add or modify your environment variables you need to reboot the app so that's why i'm just going to come back here and you can see here it loaded and from that new file i just created but we still have the error because this doesn't exist yet so let's go create it so new folder mocks inside of mox we're going to have index.js and this file here because we're using nextgs it needs to handle both in the browser and on the server so we need to be able to differentiate between them because mock service worker uses sort of different mocking mechanisms depending where you're running in the browser it uses a service worker to intercept the request and in node on the server i believe it sort of over it like overrides fetch and sort of intercepts things that way but i'm not entirely sure anyways so to check whether we're on the browser we're going to say if window sorry if type of window is not equal to undefined that means we're in the browser basically and what we can do here is we are going to bring in a worker um from we're going to bring it in from the browser code here and with the worker we're going to basically tell it to start so we're in the browser we're saying service worker start intercepting the requests so we need to go inside of here now and create a browser.js file and here we're going to set up mock service worker so we're going to import setup worker from msw and then we're going to import our handlers from a file that doesn't exist yet handlers and i'll talk about what handlers are in a second basically each handler represents one apa endpoint to mock so we're going to export our worker calling setup worker passing in the spreaded handlers so it's going to be exported here as an array and then we're going to spread that array into the setup worker function so that's all that's in this file it's pretty straightforward so now we can go inside of handlers.js and in here we're going to import just one thing called rest from mock service worker so mock service worker can mock both arrest calls and graphql calls so here we're just importing the rest ones and i'm just going to set up some data that will be used inside of the two mocks that we'll be creating so these are the coins and it will be equal to basically we're going to include two coins we're going to have cardano which is ada token cardano and its website is https cardano.org like that and our next coin will be dot so this will be polka dot and its website is https polka dot dot network cool so those are the sort of data we're going to be including in our mocks and now we need to export the handlers which are going to be an array where each one represents one sort of endpoint to mock out so the way you mock out an endpoint is you use this rest that we imported here and we can say we want to mock out a get request as opposed to like post or put or whatever here so the end point we're mocking out is slash coins so whenever you see that request basically don't actually go out on the internet and do it instead i'm going to tell you what to respond with so the second thing we pass here is a an arrow function that will receive info but the request the response and context i messed up something boom boom boom boom boom is that right i think so no boom okay so inside of here what we need to do is basically return a response what's the browser going to receive as the fake response and the way we sort of build up the response is using this context so context can set things like the status so we could set the status of 200 you don't have to do 200 because that's automatic just to sort of show you how this works with multiple maybe we want to imitate a delayed response it's a little bit slow we can say here context.delay of say 500 milliseconds and then we can give the json response that is going to be actually sent to the browser so what we're going to do here is basically just convert this object into an array of coins so here we will say object dot entries of coins and then we're going to map that we're an arrow function and each one of these it basically gives us the the key here so the symbol and then the rest of the data for that coin so we are going to return an object that will have the symbol in it and whatever is in the data so we're ending up with an array that basically an array of objects where it's this data plus the symbol of eta okay so we've set up our handler we can now basically go back to our home page that we're working on and we can see if it has data to work with so if i refresh the page it's loading for a second because remember that we added in that 500 millisecond delay but then we get the actual response so if i go and i look at the coins endpoint it's going to look like it was an actual request but here on the status code you can see from service worker so it actually didn't go out on the internet it got intercepted by our msw service worker and the response it got back was this array of coins or symbol ada name cardano etc and the cool thing if you go into console here it gives you a little message that mocking is enabled and it also shows you each request that it's making along with sort of the the status the delay um the body things like that so that's pretty useful if you go inside of the console here so we're just going to basically finish out this page really quickly so we're going to import link from next link and then we're going to replace this where we're going to iterate basically over the data so map it each one represents a coin and each one will be a list item inside of our ul so the key will be the coin.symbol and then inside of here we're going to have a link with an href that takes us to slash coins and then the symbol so coin.symbol and then in here we'll just put the coin dot name like that so if we were to come back here now we have a link to slash coin slash ada and then slash coin slash dot if we don't want it upper case the symbol we could just add what is it two was it to down case no it's too too lower case there we go okay so if i click on cardano it brings me to this page slash coin slash ada this doesn't exist yet but we're going to go create it but this time we're not going to do it sort of in the browser we're going to do completely server rendered which means we'll handle mocking in a slightly different way so first we need to create this page that we sent the user to so we're going to inside of pages here you can delete the api we're not using this at all so we're going to create a new folder called coins and then inside of coins we need a file and because this is dynamic could be ada it could be dot it could be e btc whatever we need to create a dynamic file name so we do that with square brackets symbol dot js and then in here we can create our component that we're going to have so export default function call this the coin and for now we're just going to put an h1 that says coin so if i were to refresh this now it should say coin but our goal right now is to basically load the coins data on the server so we're going to export a function we can export async function get server side props and in here we want to receive the query so what is the query it's basically any query params that were sent to this url one of which being what symbol was actually sent because this is dynamic so what we can do in here is basically use the query to get the symbol so we'll say const symbol is equal to query dot symbol and we'll say to upper case so we'll put it in the right case and then what we can do is make a request to a fake endpoint that doesn't exist but we will set up mock service worker to intercept it so what we're going to do is we're going to say const response and that is equal to we're going to make a fetch call to say some fake website https coins.com slash and then we'll just embed in here our symbol like that and this should have been a wait because it gives us a promise back so what i'm going to do is i want to check the response of the server because what if it responded with a 404 or something like that so if response.status is equal to 404 we're going to basically tell the response from the server to go redirect back to the home page so we're going to return an object that says redirect and we will redirect it to first of all it's permanent we'll say false and then i think it's destination will be the home page so unless i'm mistaken this is how you basically return a redirect from server side props and next gs so if we get down here we basically have the data so we're going to say const data is a weight response converted to json and then we want to return this basically past this data as a prop to our component so we're going to say here's the props and the coin will be whatever is inside of this data here okay so before we even go and implement this component we need to mock out a call to this endpoint so i'm going to just keep that in mind that what this url looks like and i'm going to go back to app so remember we require our mox which would be the index of this folder and up to this point we only handled basically when it's in the browser so we're going to add an else and inside of this else what we're going to do is basically set up a server so we're going to import that from dot slash server which doesn't exist and then we'll tell the server to listen so i sort of wish they used the same function call basically in the browser it's start on the server it's listen but you're going to see that they're very similar so we need to go create server.js and inside of server.js we need to import setup server from msw node and then we're also going to import our handlers from dot slash handlers and the cool thing is we don't have to change the handlers all at all client versus server but we will add a new one so now we export our worker which is setup server spreading out our handlers oops this wouldn't be worker then it would be server so export the server called the setup server with the handlers perfect so going into handlers we are going to add a second one to our array of handlers so what we're going to do is we're going to say rest.get but this time we'll put in a full url so we'll say https yep https colon slash slash coin what did i say coins.com back to server no handlers yeah coins.com and then slash and here we can put in sort of a placeholder so colon symbol because that part of the request is going to be dynamic so now we have our arrow function and this will receive the request the response and the context and then what we're going to do first of all is just let's make sure that our symbol is uppercase because we don't maybe they'll pass it lower or whatnot so we'll say symbol is equal to and how do we get the actual value here like ada or dot or whatever what we do is we say rec.params and then we can access the symbol and we're going to convert it to uppercase now we'll use that symbol to basically try and load our coin data from this little object we set up here so it's data is equal to symbol at sorry coins at symbol okay so what if they sent us a symbol that doesn't exist what we'll say is if type of data is equal to undefined what we're going to do here is return a response where we basically set the status to 404 so we already handled that on the client not the client but in this function here basically if the server returns us a 404 redirect the user to the home page so now we've basically set up our handler to to also handle responding in different ways depending on what the symbol is that was passed here and then once we get here what i want to basically do is return a response and i'm going to just return the context json of the data but i want to basically spread in the symbol and then the rest of the coin data like that cool so if i were to come back here to here we could console.log what the data looks like so if we refresh here remember this happens on the server so we come down here and we can see here that it's giving us symbol of ada cardano and then the website we've already passed this as a coin prop so we can come back here and we can say we're going to receive coin as a prop and maybe we'll put this whole thing in a div and then in our h1 we'll say coin.name and then maybe coin.symbol and then below the h1 we'll do a p that has a link in it to the coin.website and then maybe we'll just output the coin.website here so refresh now we have a server rendered mocking data from a fake endpoint we could go back to the home page and we could click into polka dot and you can see here we're we're mocking out dynamic data using the the symbol that was passed in and if we go to one that doesn't exist like btc it's going to just redirect us back to the home page which we handled so that's how you can use mock service worker to mock out requests both that happen on the client in the browser using the service worker approach but also when it happens on the server side such as the is the case with um anything that happens inside of get server side props we can mock out things there as well and it's handled in sort of a very similar way where we basically check what environment we're in and we can set up our either worker or our server to listen and intercept those requests using a standard set of handlers but i also showed that these handlers can contain unique sort of dynamic components to the data for example you can capture what symbol was passed into the url and you can load some fake data depending on that symbol or you can handle different responses like 404 for when it when the data is undefined okay that's it for today hope you enjoyed the video take care bye
Info
Channel: Leigh Halliday
Views: 6,858
Rating: 4.9641256 out of 5
Keywords: http mocking, mock service worker, msw, mocking in nextjs
Id: HkWciooQVvA
Channel Id: undefined
Length: 25min 53sec (1553 seconds)
Published: Sun Apr 11 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.