Testing with Jest: From zero to hero

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this video was brought to you by log rocket the front-end performance monitor that records videos of user sessions along with logs and network data surfacing problems and revealing the root cause of every bug tried today at love rocket dot-com / YT hello and welcome to this video where I'm gonna be showing you how you can go from zero to hero ingest so what is Jess Jess is just a JavaScript testing framework tuss actively maintained by Facebook and today you'll find a lot of reacts typescript nodejs angular View developers using Jess to test their code just is actively used as well by many people within the community but big companies you'll find big companies like Facebook Twitter Spotify Instagram Airbnb and many many other companies even mid tier small tier companies using jess for how easy is to test your could I use just a lot to test react code and I generally helps this alongside react testing library and I find that works really well but in this particular video as can be showing you how you can basically speed up your Jess learning within the time I guess it's actually to watch and go through this video so let's basically begin I'm gonna be showing you quite a lot in this video and it's going to be going over some of the simple stuff and some of them are advanced stuff like mocking spying but to start with I have this initial basic cell this is basically a great react app that has a debt as a GSM file within this file you'll see that we have an array of four pizzas and an array of four pizzas but these are rays are obviously objects as you can tell we've got a few properties in here like ID name image description price I'm going to be using this to test basically the frupa of our expectations our lengths our properties everything you can imagine I'm going to be testing so we're going to be going quite deep in terms of testing every particular piece of this objects that we have within this area so we've got four of these and we're going to be testing them individually so I'll show you how to do that as well so if you just want to take a quick snapshot of this maybe fill it out with your own implementation because it's not very specific as to what we're going to be doing we're just using this as a data point to show how we can use just we're not going to be looking at stuff like coverage today because I don't feel that it's very relevant to your knowledge I'm trying to give you a quick crash course in jest so to begin what we're going to have to do is we're going to have to import this file so this is a piece of file I'm going to call it I'm just going to import it simply like that next what we're going to be doing is where I want to show you some of the good things in GS and some of the buffing ingest at the start of the I guess the react commune in testing we found that a lot of people who were snapshot testing UI components and it wasn't very necessarily a good thing to do so that's I guess the community's kind of move moved away from that but I want to show you how can use a snapshot and snapshot snapshot testing is very good when it comes to stuff like graph QL where we can look at the input and we can get the output so if you're interested in that have a look at like black box testing or integration testing in graph q are some really good examples but let me show you how you can snapshot test this particular Jessen file because in this case it kind of works we want to see what the data is in a JSON file and we want to make sure that over time if someone is using something like circle CI or teamcity that if we don't expect this data file to change it will fail the test and fail the build which is good for us as developers so let's jump in let's start out with a basic test statements are changes to test and what we're going to do we're just going to name this and when you name in your Tessier like you'll see it's like a function we're just passing something and we're passing in a name and then a callback function we're just going to say the Pete said it's correct and when you run this within I'll run this shortly in here and this is editorship on the Left you'll see that this particular title comes through so can see if it passes or fails which is really helpful so we're going to be using here basic expectations and to do a snapshot all you have to do is we're just going to set expect pizzas that's our JSON file to match a snapshot and when you do this basically what it's going to do is going to create a folder in here called snapshots and then if you change your DHS and file them run the tests it's going to brick and that's good because then we know you know something's changed when you we need to go look at that so let's go ahead and just run this source a yarn test I'm going to make sure let's put this aside we're having a coverage I'll pull that so it's running now it should create the snapshot for us and then we can start checking against so there we are we've got one snapshot written that's perfect and we can take a look at that snapshot and here we are we've got the array of objects and it's basically using well our title that we've given it and well you know what let's take a look at this let's take a look so if I go into des and now so we've seen there on the Left we have a passing test and I just change this idea to five and I rerun the test this should fail now there we are so what it's seen here is the snapshot has changed and basically to update the snapshot you if you're using interactive testing you can just rerun the snapshot if you're like me and you're fairly lazy I just basically delete the snapshot rerun it and then it'll pass the test what we're going to have to do now that they well look it's passed the test is we're going to have to put that back two three come back in here delete that snapshot rerun this there we go perfect it's written the snapshot so now let's do another expectation an expectation just saying you can just do like expect one to equal one and we can run that and I generally keep as either search or terminal up on the left just to see if we've got any failures I only basically use it as a reference generally what I will do is I'll have my card terminal and then two vs card and then I'll have the coverage once I've written all the stuff that I'm expecting so let's go sir expect pizzas to have a lymph four and we basically said now do we have an array with four objects inside we do if that comes back as false then we'll see in the terminal I don't expect it to come back as false because we've just had a look in our JSON file and we see that there's four objects in now so next let's do pizzas dot map and we'll do a pizza pizza a.m. so we're going to basically get all the pizza names here and we're going to say we want to test that these Pizza names equal what we've got in the data JSON file so for a bit of brevity let me just copy that and the next one is New York Pizza which is always a good choice and the next one after that is Sicilian pizza I knew if I try typing them out myself I probably would have got a failing test but let's just take a look so that should hopefully pass perfect that's perfect so now let's take a look at how we can test each object within our area and we want to check for the properties so a good way to do this you can use I believe it's dot each maybe just match in for each I find that quite complex because you have to give it in the rear of your values and the expectations in here I'm just gonna use a standard loop so you'll see here I've got options in base code for basic for loop for each loop for in loop and a far-off look I'm going to go with a basic for loop here I'm just going to set eye for the index and I'm gonna change this to pizzas don't limp and then we're gonna do I plus equals one just check that down and now let me just scroll a bit thing see this better then we're gonna say we're gonna write a test here I'll change this to test again generally if you've got a test suite so you've got describe and then inside that describe I use it if I'm just running singular tests one after the evaluate X so what we're gonna say here is let me get some template strings please and then what's a pizza and we'll set the iteration which is gonna be I should have properties ID name image description price and it doesn't really matter how long your test title is because I prefer them to be longer than show because the person who's looking at it will get a better indication as to what's going on so we can test each property now in here so we'll start looking for the ID the name the image description and price granted we've got some backup on the snapshot so if anything changes but I want to show you how you can use both ways essentially so I kind of prefer this where as opposed to snapshot because and I'm not pushing most of up to get but either where works so we'll set pizzas and what's that I and what sir to have property ID and we just copy that and what changes to name image description and price and just to check that this is working we can just put in crazy price in there so should get a failing test which is good let's pull this over there we are perfect so it's receive the value description crazy price does now exist pretty much so so it's good to put in something that do I expect just to make sure your test isn't passing for some weird reason but that's how you test the properties by looping over each particular item within the array so now we're going to get onto mocking so what exactly is mocking well the way I first looked at mocking when I started testing is you know how you've got like a joker or in a pack of cards you've got a joker or I think in Jasper it's called a cow quite remember but you know how they mock people well you have to a nail make a joke maybe how you sound or how you walk or how you look you know something really silly that's how you have to think about mocking so mocks and known as essentially spies that's what the known adds or something that's mimicking something so instead of hitting Axios for example we don't be pulling in the entire axials library and making it hit the actual remote URL that we were using for our api we're going to mimic that and essentially in a certain words win the market and just give us a thick maybe an object of function whatever it may be we're gonna be mimicking the behavior so we're not going to be directly hitting an endpoint in the case of Axios we're going to be indirectly hitting some other piece of card that we've grid and it's much much better than testing the output because what happens if you've got like a build going from team city or circle CIA and trying to hit the live endpoint and you know you're running that test multiple multiple times and it's costing you maybe you're a small company it's costing you money there's no need to do that and plus what happens if it goes down it'll break all the builds so it's always better to have a fixture or a mock so let's look how can you some basic mocking let's go down here and we'll just say again we're going and we'll say test and for the title we're going to say a mock implementation of a basic function so when stuff with the basics here we'll set mock and give that this constant will just say Jess dot FN and I'll get to shortly and we will return I am a mock function so let's go ahead and log that out what does not give us so I'll run that test and there we are so we get a lot of helper methods see us so we can you know mock reset restore return value ones implementation ones so this is stuff we're going to be looking at which is really useful and you'll generally find your user a lot if you're working in a company or on a project I'll just generally using react in your testing code so let's say expect the mock call in my mock function to be we're going to use the to be and it's also like to be true fear to be false here to contain and a bunch of our helper methods that we can use in validate against and there's a there's some sort of differences so definitely check out the jest documentation this website is just Jas dot IO it's very helpful so we'll see I am a mock function and what's happening here is basically we're going to be calling this mock here we're going to be passing something in so calling my mock function and we're gonna say is it a return output I am a malfunction and that's all is so I'll do the same again will expect Mach to have being called with even though we're not been doing anything with this here we're just going to grab it and we're going to see that the function got called with this particular argument that got passed in so let's go ahead and see if this works pull this over oh it doesn't work so there's a good mistake from me here so we expected I'm a Mach function and we received I am a monk function so my grammar and this one's not particularly great I'm saying I am Mach function so let's go ahead and change this I'm a muck function I'm a Mach function where we're looking here to be I am a malfunction okay I am I'm not function okay I see it I see it I see so let's pull this back over here so saying Here I am a Mach function let's put this to me that looks exactly the same no it doesn't I cannot see the air so perfect akia that grandma's better if we rerun that test we should get a passing test perfect and you see how we've got all these titles coming down now and we've got the loop going as well she's grip so we've got five different tests going on here and we're starting to build some real confidence in this dear file that we're testing it's not just a data file here we can apply this to components we can apply this to classes whatever it may be the stuff you're learning here like testing objects testing areas this is the real fundamental stuff and testing now to mock it's very very important so moving on there's a difference here so you'll see that you'll use probably Mach return value quite a lot you'll see mock implementation quite a lot and I want to start off with how we can use Mach return value so if I just move that up a bit and for brevity let's go ahead and just delete this and we'll change this one to Mach return value of a function one time so what does that mean sir you can mock the return value as many times as you like but in this case was going to mock it at one time and I'll show you some good examples right now so if we just create another mock function again and if we do mock dot mock return value once so we're just gonna say okay when someone calls it's the one time give us this output if you call it the second time then there's not there's nothing that's going to get returned that we expect right maybe it comes back with undefined so let's just say hello and the good thing about getting all these helper methods on this mock constructor function here that we've got up here is that we can chain these so we can do this twice so if I wanted to just put another one there I can just put Halawa save that and we can do that twice how great is that so now if I call this twice this function I can do expect mock to have been called times two so that's just saying as a function being called two times if it has passed the test it's been called three times failure so what we're going to do next is we're going to set mock hello and we're going to pass in there and we're going to pass in Steve so you can see I get kind of crazy listing passing as many arguments as you like and we're just going to be testing the stuff that's coming out so here let's go expect mark to have being called with so if you're passing in the user on a live website and you're passing in some important details we can test that the user is passing in say their first got an email address and some sort of password we can you know just give some dummy data for those two parts but we want to make sure that the output does it go hit a session remote server where we can see for the session our eggs-it already existing so that uses products in the basket you know something along those lines so here we can say hello there Steve so what's going on here basically we call it calling the function twice here we're going to expect it's being called twice and then we're going to call with three different arguments and were going to make sure that it's been called with these three arguments we can see that we're gonna get a failure here because I've give it an exclamation mark and that's good because it's always good to get a fill-in test and see why perfect so we get a number of calls here three so a mock return value of a function one time is failed which is this one here and if we get rid of that there rerun this test we should get a pass in test suite perfect so we're definitely building some confidence around the stuff we can use now so let's go ahead and do just a singular one so we'll just set Mach Steve expect Mach to have being lust called with Steve and again that should pass I'm pretty confident that pass I'll start read running the testers will get deeper in you don't to write a bunch of tests and not run them because you may run into an issue way like wow I've got three out of five failing tests so let's go ahead and create another test here let's move it up a bit and this particular one this particular test I'm going to show you how to use mock implementation or the function so if we go ahead and do mock again we'll do just that function dot because you know we got all those health and methods on them we saw we have mocked implementation well what can do we can just pass a return value of a function and I'll set United Kingdom and that's going to get returned so if I say expect mock location to be United Kingdom so if we pass in location it's going to give us United Kingdom the locations are relevant in this case because what I was going to get United Kingdom back but you can see I can applies to some real production or just God that you enjoy you're working on so I expect not to have being called with location so you see how with the mock return value a bit so it's giving it a return value immediately with the implementation we're saying here's a function go ahead with so we've got like an anonymous function going on here saying yeah go ahead just you know the implementation isn't basically a callback function in this case and return in United Kingdom if I go ahead and serve that so in this case I think it's probably a good idea now to run the test because we have written another one and want to make sure it passes and there we are so it's saying here mock implementation is not a function now I don't know if this is me not being able to spell but let's try that one more time let's see oh it's not and the reason for that is because I didn't call the function so I have more confidence in my spelling now as opposed to figuring out just nevertheless let's move on that one works perfectly the next one we're going to be looking at is how we can spy on a single function of an imported module so if you've got say a kiosk for example imported and you've got some test that you want to run against well you'll generally find you'll have like get dot post and you don't want to be using the actual implementation so you can mock those out so in this example I'm going to be showing you how you can spy on this so if you've got say a class as well if you forgot a class and you have an object in not an object a method in there that you want to spy on it's much easier to have a look at the actual implementation one key factor is we've spying that by default you will get the original function that gets called so if you are using dot get in a kiosk it's going to use the actual implementation so let's say spying using original implementation and then once a Const pizza and we'll have a name and we'll you know use the argument name in here we'll set pits in there and then we'll just say and so we're just going to basically passing in and it's just gonna print it out peace in here with what we passed in put that there and when I says spy equals just dot spy on so now we're going to pass in this pizza objects and then we're gonna say good look at the name and if you had for example another one here like a pizza how old is a pizza where you could pass in them edge here as well if you wish not at the same time but differently so now we've got the spy we can say expect pizza named cheese shabby Pete's and named cheese because we're passing it in it's just going to basically put it in where these red brackets are and that should pass and then we can set expected spy to have being called with cheese and I'm pretty confident nut should pass but again we've written a new test so let's go ahead and just check it let's see there we are that passes perfectly so next let's look at how we can get into the juiciness of spy because spy is very very useful and sometimes you want to check in like like I said earlier maybe an employed module and you just want to change one of the functions or whether it be a class or whatever it may be but sometimes you don't want the actual implementation so that's where we use mock implementation so you can see how all this stuff ties together right you've got all these assertions like checking knives being called with to be and then you have the like the mock implementation and the mock return value there's a bunch of useful stuff so let's actually you know what can pretty much just copy this one because there's not that much to change so we'll say spying using let's get rid of Ridge original mock implementation and then we'll keep the peace in them here then we'll say spy on spy known that looks good and at this point this is where we need to change that implementation so going to set mock implementation I'm going to check the pizza name because it's pretty much the same and I say crazy pizza let's pull it up a bit and they'll say expect pizza named cheese to be well now to get a passing test we need to put crazy pizza in there then once that expects pie doctor have being called with we can get rid of that so see if that works let's go ahead perfect that one works so let me pull that back over there so we've not the implementation we've done an expect so what happens if you want to use a method in there for example that comes after the spy or you want to use well not comes after the spy sorry if you want to use this particular near method but you only needed to mock it in one time well you can restore so we're gonna say mock restore and we're going to put it back to its original implementation and then we can make sure this works by doing it expect pizza named cheese to be Peter named cheese and we can test that works let's run that test and it works perfectly brilliant so I'm making some real progress here we've looked at mock implementation mock return value spying we've even looked at mapping over doing a for loop of a each particular object in the area you see I'll just is really really powerful on it's very very easy and I know what I'm saying it's easy because I've used it but when you look at other testing frameworks oh they're Hutton some of them really confusing just gives you all the nice names to use like to be there's no there's no like you'll see many annoying jest you can do this where you can do like mock dot something dot expect dot to be dot object I mean it's just much nicer to be like to be you know so yeah just as nice and I now says it's easy but it'll become easier any easier and easier as you go on and keep writing card that's all it is there's nothing special here it's just muscle memory and going over and doing it time and time again that's all it is so next any Hill let's take a look at another test obviously but this one is going to be a bit different so I'll put this one too because we've looked at some of the juicy stuff like mochi and spying I said Pisa returns New York lust and what does that mean well let's go ahead and access the pizzas rare so we're going to get the first pizza out I'm gonna get four pizzas sounds like a good pie actually Falls probably too many let's just go with three and we'll do one two and then what we're going to do here it's going to say pizza equals Jess function we're going to use that Jess top function again you'll find yourself using that a lot on what's a current pizza Karen p.m. so what is this doing exactly well we're passing in an object to this Jess top function it's just going to check out the name property which as you see right there so we should hopefully if we pass in pizza piece of one we pass in piece of one to this function we should get Chicago a pizza I believe yes the next one you'll get the Neapolitan pizza I think and after that my favorite pizza the New York slice New York slice pizza so how can we test this well let's go ahead and say expect pizza to have last returned with New York Pizza so we're calling the mock function of three times first value Chicago then Neapolitan and then the last one will be New York Pizza so let's test that works let's go ahead have a look perfect so there's many many different ways to test this but we're pretty much testing as much as possible here through the the JSON file and again looking at how you can you'll find you're using arrears and objects and that sort of stuff quite a lot with it's a react view basic JavaScript typescript wherever it may be and implementing the stuff you're learning here into it's very much just a switch of it's not gonna switching mindset it's just to switch up okay we're not thinking about pizzas I'm thinking about products even the piece there is a product and it's one of the best products but that's what I thinking about so let's go ahead and do some data matching which is going to be good so me being lazy I will just copy that so we've got an empty test here and we're going to say pizza there has New York Pizza and matches as an object so as mentioned these many ways to test stuff so let me go ahead and get that New York Pizza go back here and I'll say New York Pizza save that perfect and then down here we're going to say expect pizzas - which is the second item in the array so we've got 0 1 2 2 much object New York Pizza so we're testing the date file against our basically our you could call it fixture it's a fixture really what we've put together we want to expect that's assumed so let's go ahead run that to make sure nothing has broke we've got 11 passing at the minute I expect this should be 12 perfect there we are brilliant so next what we want to do want to start looking at some of the stuff that you're running to when you're making calls to say back in services I'm making some sort of Axio scoffs you'll find actually quite a lot within like reacts I generally use graph QL but I also a lot of the time use actually ask both have our advantages and disadvantages buffer really good but pick your poison in that case so let's go ahead and create another test and we'll just test and then what we want to do here want to look at how to use async a way so let's expect to promised to resolve so any sort of icing function right he's going to return a promise so you'll see here I've got a test I want to make this async all I do shove the async keyword right there and now let's do const user equals get form them so let's just create an object that has a function in here a mach function and we'll set promise resolve resolve it to my name kyle huh Duane give that a sieve and then the expectation has to wit right we don't want just to run over to the next test so we're gonna say a where the expect user get full name Kyle hard win and we're gonna save resolves because that's what's gonna do to be call huh doin and that's how you doing this increase' test oh it's nice very nice so let's run this make sure it works beautiful so it's so so good so next let's take a look at a rejection sir-sir rejects expect to promise to reject all we gotta do here would get the full name and then we'll just reject but when you've got to reject you'll see that I've got a little squiggly line here to say you should fro rejects ok I'll do a new error something when terribly wrong that does sound very very bad so if we pass in the full name we don't really care about that but we can just say to be something went terribly wrong and let's run that and that should be well pretty much coming to the end of all the testing oh we have an error did I check all resolves okay you see here this is what happens when you copy and paste it always seems to get me it let me reject that I see oh we still do expect a promise to reject to be often defined okay so we have a new era with rejecting we have a function a we're expect user to target for name Cal hardware it rejects that now pass hopefully no error something went terribly wrong oh I've done to be you want to do to the row now that should work because then it knows it's an error that's coming back because it's run in error and we're expecting an error and that should pass fingers crossed there we are so I'm gonna wrap up here we've seen how we can extensively test you know areas objects date files by using some really cool stuff so we just go back to the beginning we've imported a JSON file for just a mock there basically we've done snapshot testing we've checked the lymph we've gone ahead and maps over and match all the names exist then we did a nice little loop of the properties of each object in that area then we had a look at the implementation by just like mocking out the implementation checking it's been called wave we looked at basic Jess mock constructors we then moved on to look at Mont return value mock return value once checking on the Tom's it's being called checking what's being called with and then we looked at the implementation so how can we mock the implementation as opposed to just returning a value furthermore we looked at spying how can we spy on a function from a module that's been imported and how can we also use smite or advantage to return the value back to its original state well we use mock restore in that sense next we basically create another mock function we called it three times we assigned three different pieces in here and then we call it three times check that the last one it returned with was the New York Pizza after that we had a fixture small or fixture that we put together basically is just an object with this data that we're expecting so we're saying okay the piece are at Value Index two is going to match the object that we have created here after that we look to how we can use acing a weight so as always if something is marked as async it's asynchronous it's gonna you know hit the micro task queue is going to come back and return a promise we have to resolve that promise so what we did here we don't want Jess just skipping over and got moving out to another test well what we wanted it to do was we wanted to where the return value so can make sure that it expectation is as expected likewise we did that with the reject so that's quite a lot to take in go ahead create your own date file or maybe your own components I do recommend react testing library if you're using react to put alongside just very very useful but yeah that's it that's there's a ton and ton and ton of more matches that you can use online go check out jest js2 ir check out the documentation it's very very useful the stuff I've shown you too today it should help you get by and basically this should prop you up to 80 90 percent the other sort of stuff that even experienced devs do senior devs you know even tech leads who is still program in that sense will also be checking out documentation so don't feel bad for checking the documentation everyone does on a daily basis now everyone can remember every one of these expectations or these assertions I should say so yeah thanks for watching the video I really hope you learn a lot and have a wonderful day goodbye
Info
Channel: LogRocket
Views: 44,383
Rating: 4.754601 out of 5
Keywords: jest testing, jest testing tutorial, javascript tutorial, javascript, web development
Id: NHMIn723hQY
Channel Id: undefined
Length: 36min 55sec (2215 seconds)
Published: Mon Apr 06 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.