Mock Service Worker Tutorial | How to Mock Network Requests

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone hope you're doing well just before we get started I wanted to say a quick thank you to everyone who's subscribed or watching my videos we just hit 100 subscribers yesterday so that's a huge milestone for me so thank you very much so today we're gonna be looking at mock service worker or MSW which is library that allows you to intercept Network requests on the browser or within an old environment essentially mock responses back so this is going to help you out for the testing side and for your development story as well so there's quite a powerful tool I think it's very kind of simplistic and its approach and the mocks you right can be shared across both your tests and development so what this means is that in your tests you no longer need to kind of mock out windows or fetch or mock your kind of fetching API service and you did all the mocking in the network layer so that's kind of a lot more a lot more clean a lot simpler we'll have a look into that from the development side it means you don't need to you know spin up a back-end or point of dev server you can still all within the the browser and you can really easily change the responses again from the network level so very powerful tool let's let's get right into it so as a prerequisite I probably recommend just having a quick read about how service workers work I'll a link in the description below for you to have a quick read I'm gonna walk a high level what we need to know for this tutorial here but I won't cover everything of course so if you just think of our standard request from the browser and I'd you just calling up to an API server from the browser server and you're gonna get the response back and so one thing that service work allows you to do is intercept the traffic right so if you open up the browser and we see we've got our code here and we've got this kind of service worker saying just in front of there in front of the code it's got access to all the network requests going out and coming in so you can see how you can build up some powerful functionality in terms of offline caching etc and if you had a serviceworker so what NSW have done essentially create their own serviceworker and that works side by side with the mocks that you create in the code and we're gonna have a look at that soon and it's essentially going to return the box so when I'm gonna go out to the server toll the feedback loop is very quick and it's all going to be within the browser but from you know perspective it looks like a real Network call which is which is why I think it's really powerful so yeah let's get into it so I've got very simple application here I've just created it with the create react app I've added some CSS I'd like to point out as well that I've also added the JSON 16 environment to our text so at the time of recording react for test is still on an older version of JSON so there's a bit of an issue around back with testing so to get around that i tattooed an NPM install JSON 16 and had that there in the future you might not have to do this because it'll be up to date version so a comment in the pen section below if you no longer have to do that so yeah so I've got this very basic app which is essentially just doing a fetch to a user API and displaying a walking welcome screen or an error message if if it fails so we just have a quick look at this code and look at the test and I will introduce MSW so we score a couple of local states want all the user name and want to hold the status of the API response so in EIU's effect that's just running when the app is first rendered were doing fetch user this is just a function that does my fetch to an API this is just low post API Savior it doesn't exist so you can see on the right-hand side here make sure infused the API doesn't exist we'll fix that later on and of course if the API fails we're gonna throw an error otherwise I'm gonna return the response I'm gonna assume the response has something called username so we said the username we said success and if it fails of course we catch the error and we set the status and then we're just ready and based off of the stated so either an error loading or the welcome message so hopefully that's fairly simple and we'll just have a look at the test now so we just a very simple test and this is just checking that we have the loading message right so if i refresh this you can see very quickly though you can see loading there for a split second and then we're just using our way to it to make sure that the welcome is in there is in there in the screen so obviously if I run this test now gonna fail so what we're gonna do I already got test running so I'll stop this one we're gonna do in this exercise is we're going to introduce MSW to get tests to pass we're gonna introduce second test to make sure we can test it failing scenario as well and then we're going to take those mocks that we've added for the test another reason for development so yeah let's see how that works so I've got my test running here it's obviously failing just like we'd expect the physics seeing a fetch user but it's expecting to see welcome right on so I'm gonna do is you're first gonna npm install and that's w so you're gonna run that and already run that song you're not gonna run it again and we're gonna go into our source directory and we're gonna create file we're gonna call this I'm gonna call this handlers and this is going to be essentially all the box right and all the market guys that we want I'm gonna go inside this file for now and we're gonna use these in our in our text and development environment so we're going to create a list called handlers and we're gonna use the MSW REST API so it's worth knowing at this point that MSW supports rest and graph QL so if you're using graph do this in a work for you this one is going to use rest and then we just basically build up the API that we want so in this case so get requests and you give it the mask which is basically API they want to use and I think yeah just a local host 8080 API slash user as a first argument and the second argument you gonna take in and standard resolver so if you're used to you know you playing around with node exciter this is quite common for API requests so you have the request an object which has got everything from the body their URL the headers etc we have the response which is what we're going to respond back whip and then we have a context to build up build off the response so what we're gonna do here is we're gonna return the response which is that function and inside this we're going to use context and we're gonna say for example in this case was gonna return 200 and we're gonna give that one a body I think correctly the body had user name I was just reading nuts there we go I've got the equal sign there and that's it that's all we need to do so I've mocked this API and it's gonna return 200 with that username so I'm trying to export export handles I'm also gonna export rest here as well so we want to specifically use this instance a tresor and export it we're gonna reuse and the test to create handles at runtime so you'll see what i mean by that in a moment so once we've done that we're just gonna go over to our test and we can just memorize this and at this point what we want to do is sell this server in the known environment and before all the tests want to start the server we want to stop at the end of the test and we want to make sure we reset all the handlers after each test just in case we're modifying them in run time so what that's gonna look like is with the server's equal to setup server and just reminder know that we have server and worker so browsers support service workers but they're not really a concept in the node environment right so what and I stop we have done is basically create an API that takes the handlers and kind of loops similar for for both so if it's ended in a browser it's gonna create an actual service worker to intercept etc but for the server so I'm gonna do that's gonna do something else we had the scene so they've they've handled all that for us so from the server will be we're gonna destructor had those inside there and then here we're just gonna I'm just going to paste in a bit of code which is just starting the server and ending the server after all tests and resetting just like you said and also we need right so if I now open up my test which is just running we can see that it's passed brilliant so the test is rendering the app which is making an API call and that's returning the right responses so I'm welcome Baronessa so what we want to test a failing scenario I see that looks like so I'm gonna do placate this test I've bring the style bit so it renders welcome message to let's say the red race error message when user fetch let's just say fails cool so of course this is gonna fail at first so let's say era fetching user I think that was the end I think that was the message I'm just gonna let this run so of course this is a fail and that's because the API is returned in 200 so what we need to do is we need to essentially override that or add another handler we can do that by using the server object that we've there Sanchi eight up here so I'm just gonna go server use and then here you just pass in more handlers right so I'm gonna go over to my handlers and it's gonna copy and paste this guy I'll go back right here and instead of returning a 200 with an object I'm gonna return our 400 what's that and hopefully if I save this and just wait for the test to run mmm that's failing I think it's because there's no full stopper they know and so yeah Eric Fletcher user and that's exactly what we're saying and you can see how you could start to build this up to be a bit more complex to you know look at the request headers they request body etc to build up the kind of logic that we need great so now let's work on getting our development environment so it out so there's a command that you need to run up as a one-off and basically to add my serviceworker to your file and what you can do is you can want MPX and MSW in it and you gonna point this to your public folder so for create react app point it to the public folder if you're using a different framework you can check the MSW documentation and that'll show you where that's create so you can see that elastics could just create a mock serviceworker Jess and the public folder so if we open that there there we go so that gets checked into your code you basically don't need to touch that that's something that they've created and we can essentially forget about that that's gonna hook up with the handlers with the worker that we're gonna set up and it's all just gonna say she's always going to work so we're gonna go back to our app Jess we're going to set up our work now so we only want the worker to run we're in development mode so we're gonna do a quicker saving to check the this process that have dot know them so we're going to check that we're in development mode and this is a pre confirmed environment variable we have access to and if we are in the development world we're gonna get gonna get a copy of our handlers from I think the file is hunters there we go we're gonna do I'm gonna set up the worker similar to when we set up the server earlier on so I think it's setup worker here we go I'm just gonna pass in the handles exactly the same way and then we're gonna call work with us start and you'll see when we go work at that start there we go got no more failing and failing request I've a bit fancy CSS I've copied and pasted it to make it to make it look nice and button that yeah we can see how it's working some no no expand this out a bit so we can have a quick look you can see that MSW is doing its own logging so you can see that it requests you can see the response etcetera but all you want to look at is the the network tab so we can see that there's a user request here and if I open this up we can see that this looks just like any other network request is Scott you know I request URL and let's go headers response and request and we can see that it's 200 back there's a few things that make it clear that it's from service worker so we've got the from service worker here beside the code and we've got the header that's returned by NSW and itself everything else just looks like a normal request I'm one other thing that's probably quite interesting is if you jump into application and this is on Chrome and if you go into service workers here you can see the mock service worker and is activated fan running so you can see that that's all working fine and where this really comes in powerful and if I just make this a bit small again is if you want to test out and have different responses if you're debugging and you've you know got a weird response back from the server all you do is go into your handlers you know for example change this to 400 and you stray super-fast feedback loop you've got a mock response which you can kind of debunk against test against so yes really really powerful stuff and and yeah I think that's everything for for today I'd really recommend you checking this out something I'm definitely gonna be using thank you very much for watching in there have a good day
Info
Channel: Redhwan Nacef
Views: 3,825
Rating: 4.9607844 out of 5
Keywords: Mock service worker, msw, service workers, mock, react testing library, mswjs, react, reactjs, react tutorial, Software engineer, software developer, how to, how to code, coding, programming, testing, java, javascript, learn to code, learn coding, learn programming, software, technology, computer science, YouTube, Redhwan Nacef
Id: V-CKjACOfmc
Channel Id: undefined
Length: 13min 40sec (820 seconds)
Published: Tue Jun 30 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.