How to write unit test cases for testing API built with nodeJS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys this is Manoj and welcome to recraft frolic channel I hope you all are doing really well and yeah so I'm back with a new video in this video today we will be going through how we can write unit tests for our API which are built an Express and with MongoDB and we will also go through how we can create a crud API in express so I already have a project set up I am going to show you how to create this API in a project which M I am already working on it's a personal project but you'll get the idea so I already have like a get user API so today we will be going to create a delete user API basically for this project I'm using dhoka so I'll basically start up the project or to start the project I have to do doc will compose up don't worry if you don't understand okay right now there is a video that I will be creating also you can also use to occur with you Allah no js' projects but for right now it's okay if you don't know what docker is basically so I have started my project here and let me also okay so we have the project running here so let's just get into the code okay so you can see we have this folder structure here and inside this for structure I have a routes folder inside which I am creating the user API basically so I already have this create user API here user order dot post and then I'm exporting this and using it inside my index dot 0 so here you can see how user alter and then I'm using it to the slash user a pair okay with that being said let's just jump into the code because we will be writing test cases in this application so it's always a best way to write as first before writing any code if you don't know what test cases or specifically what unit test cases are let me explain what unit test cases are and what are their benefit if you are using them so basically your test case looks something like this like this and what our test case do is it basically a code which will test your application code and see if it is behaving in a right way or in the B in the way that you want it to behave so if something is many missing or if your code is not working the way you want it to be the Reese's got failed and you can fix them so let's just get started before writing the test case in the code we have two brain strong what are tail attached cases well B so for example what will be the condition where we want to put a chat or what kind of code we want to test so what kind of functionality that we want to test if I will be surface of it okay so the first thing okay start with defining our requirements or what kind of API we are writing and what is the purpose of this IP a so let's start by this so this API is a delete user API okay and it's probably going to delete a user so it needs some kind of unique identifier to identify which user to delete so the input will be unique identifier or you can say user ID basically which user you want to delete from the database and in case if we don't pass a valid a API of valid user ID whether the user ID or we don't pass user ID at all then it should through some kind of pattern so the first task is that comes to my mind is if we don't provide a valid ID is no valid ID then we should get an error so what is an invalid ID basically what kind of definition what is the definition of an valid ID so there can be two type of invalid ID the first one is we don't provide any ID so no ID basically no user ID or corrupted user ID or you can say wrong user ID user ID which doesn't exist on our database exists and database basically so let's simplify it more and convert let's convert these or this task keys into to task a so the first test case that we were going to be right writing is if there is no ID provided then we should return an error message which says we that you have to provide user a user ID and our text second user u test case will be if there is a highly provided and that ID is not a valid ID then we will we will send will send an error which says please provide a valid user ID and the third case is very simple so in third case a case we will be or testing if everything is okay if there is a valid ID then API should return a message saying mates which says that user is deleted successfully these kisses decided we are ready to write some test cases code okay so I'll just basically going to comment this code leave this let's just keep these requirement okay so for writing test case on the test cases on this project I am using mocha and chai basically these are two assertion library or tasks is a library you can use to test case your code and also we are using request package to make the pay requests so we can test our API so let's just start it start this okay so we have chai here so let's just put it we just need expect from it so we'll just use that require chai drugs so we just need the expect right now and we're also going to be getting the request here must end our testing URL so I already saved this testing viral and our constant file I have so here it is so this is basically a test you are local host we are running the array pay on pour 300 and I created in URL of it and then I importantly so once that Bing de we are ready to write some of our test cases we start by writing a describe scoop so describe scope let you describe what our task is is basically four and this will help us when we run our test cases now let's describe our task is so this is a delete user ap so I'll just go into my delete user API and inside this we can write a code basically we have to pass a function like this and we are good to go so you can see we already created some tasks for the create user API but we are going to be writing noon test case for the delete user okay so this we described a scope now we can describe multiple nested scope so in delete user a pair but we want to test we have three test cases basically so I'm going to describe another test case here which says no user no user ID provided validation error we want to check if we don't provide any user writer to our API and if they if the IP a returns an error for that amount okay so we'll go like this and then we have to pass on the function so we can test it and now we are going to use it this is also an the keyword provided by Moka so we have to pass a title to it so when we are testing if our API is returning us error or not we will be testing two thing first thing is the status code basically what status code the pay's returning is it 400 400 4 or 200 status code and we also will be testing the content the error message that API will be sending so I am going to write firstly the status test code so this just called test code use it like this you have to provide a callback in which we will up test our API and if our API test is fine and then it will show a green flag when we'll run it on in the command line so to test our API we have to do something like this so means we will going to create a request to the testing URL less testing you are just an URL / user / delete / or to be more surface of it we can do something like this we have to provide a user ID here and then delete by doing this we are compiling compiling more to the the crud basics basically so we have a user then we have a user ID and then we have / delete to delete that user and we can define this user here user ID equals to 1 right now and with that being said this will be a delete type of the method so there are multiple methods get post delete patch but because we are deleting our user view I will be using the delete method for this so now unless resolve our response so for resolving our response we will just do this so this has [Music] first off when we don't need the false argument and then in the second argument we'll get a response basically so let's just go here and control that lock this all right so I'm just going to comment this user task is because we create user tsuki because we don't need them we just need that so you know the delete user test so let's just start them by running and PM test and let's see if our test fails or not so here you can see this is the console that we have part was controlling the response right now so we did we just about to test the response so we can just do response dot split test code and we'll see what status code we can we do the NPM test and you can see it is giving a 404 that is right because we don't have the API right now so it is giving us a foreigner phone that is completely correct so when we don't provide a user ID so we don't have to provide a user ID so let's make this user ID amputee so we don't want to provide a user ID and we want our IPE to send an error so because it will be a syntax error because we are not providing the the input that our API needs so our EP will send us a status code of 400 basically so right now we will going to use expect so I expect we already imported it here so we are going to something like this expect the status the response dot status code 2.12 400 okay so basically we are asked asking our test case that expect that the response the response rate status code which will get from the API should be equal to 400 and if it is correct we'll call the then callback basically which basically going to execute next test kisses okay now let's try our task is so we go here we type and then test and you can see our test is failing because we get the actual the actual response that we are getting is 404 but the task is expect that it should be 400 that is correct because we don't have the API right now so let's start by creating our API so we can pass this task is okay so here in the routes I already have this create user ap let's create our delete user API below this so user router dot delete and we'll basically this is the index so we have like something like this user ID / delete and then well because I'm using a sink of eight here's well have to create this a sink request response then we have this okay so firstly foremost we have to test if we are getting the user ID in the request dot parents basically so let's extract user ID from the parents and it's not provided I'm just going to assume that it is amputee so from the Rick dot perhaps and let's console this and and I'm going to just send status of 404 on just for right now you know just for the testing purposes and in the JSON I'm just okay so I'm going to console the user ID here on the second node let's just change this to 200 and message to like success or something so okay so we have so we created a utility API we get the user ID and we treat it as a para and then we have / digit in front of it then we are extracting the user ID from the parameters and then we are consulting you okay so let's just try this out that do the NPM test ok and yeah so I discovered a error basically so it is still showing 400 phone for but clearly we are sending like it wonder but it is clearly showing foreigners for the reason for this is so if I go to into my test case I am sending the user ID amputee and because the user ID is amputee the URL that we are getting is this so just let me control this controller log and if I console this and I am test you can see the the URL which is creating and it is treating this as user slash delete so in order to this are tasks to work we have to provide like a space ID so the URL ah which will create a something like this and PM tests like this and then you can see like we are getting a 200 right now because our API is getting hit now previously because we are not providing like a space in the user ID it was completely empty so because of that this this route was not getting recognized and it was not working so because we have a space known now we can also see like a consume here like the amputee user ID consoler so now we can put a check and if we found that the user ID is amputee then we'll just return an error so how are you do it basically so I'm going to put is user ID dot trim so it's going to trim these spaces from from the both ended and and and then I'm going to put a knot here so if there is a user ID with frame the spaces from both ends and then we check if it still is an valid string if it is not then we just going to return response dot status because we need a hole in your data so we are going to send a for in this status da guia song and in the message I'm just going to send and and it's work then we just contribute and so now we are getting the user ID and if the user ID is not there or the user IDs amputee even after trimming the spaces then I'm just going to return the status of the 400 and in the JSON basically I'm just going to send a message which sees hello so let's see let's try to run our test and see how that works and you can see it's passing it's passing because we are passing like an amputee user ID and because of there that user ideal amputee we are getting this four hundred so okay so if we want to make this work we can also put like user ID one here and then our task is will fail yeah because it expected to 400 but now we are getting 200 so so this test case is working so our API is a peaceful proof right now so our first requirement is done in our first recon we say if there is no ID provided then we should return an error message and which says that you have to provide a user ID so status code is working so we are getting a status code of 400 if you are not providing an user ID but now we want also want test the the content basically diagram so that we are getting so let's define another task is we say is content and inside the content we are going to call back which we got done and inside that let us take I am PT user ID or let me do one thing you know just the finite outside can be used both in both our test cases so I'm going to use the same API hit everything but now instead of checking the status code I'm going to check the error basically the same way I'm doing it here you can see response drove a little terror okay so let's just copy this and put it here okay so responsible body wrote errors zero error that we will get will be equal to you have to provide ID and ID okay user so we want that we so if the user ID is amputee then we also get a status code of four hundred and our error message will be equal to you have to provide is ready let's run the income test and let's see if it works the three this test is passing the status one but the other test is failing so let's also try to make it work now so let's go to a route and let's change this through errors and convert this into on say you [Music] user so now what we are doing we are sending a status of four hundred and in the JSON in the body as we are checking here in the body dot errors in the body dot errors first element we are providing user have to provide a user ID you can see user have to provide the user ID the reason I'm taking these errors into an array is that there can be multiple errors and in the future if you want to pass multiple errors we can also do that okay so now let's try to run this and see if the test box okay so can you read property zero undefined it series let me check writing the state is called as a four hundred let me see response start body we also have to do one more thing so because we are sending JSON from here we also have to pass it here to actually see actually decode the value so I'm just going to pass this this bonds draw body into body this constant body json dot pass and response to body inside this and now I can just further so basically parse the response dot body I into the body and now we are talking checking that body dot errors first error should be equal to you have to provide a user ID and let's see if it's working okay expected undefined two equals you have to provide a user ID it sees it is undefined okay I think I haven't saved this file yeah let's so walking okay so just to be clear let me go through this thing one more time so our requirement was if there is no user ID then we should return an error message which says you have to provide a user ID and so what we are doing from the back end if we don't have the user ID we are sending two things for first is the status code which we are sending to 400 and then there is this error message which is you have to provide a user ID so we are sending this true from the back end and we written our test is which basically tested so we try to send our you are a amputee user ID and then we test if the backend is sending this correct status code which is 400 and the corrected error message which is you have to provide up user ID and it's pocky proactive fine so when we do NPM test we get the status on content gut path so both of our tests is passing so now it's time to look into our second requirement ok let's start by copy/paste Ignace so ok so our second requirement if is if there is ID provided and that idea is not a valid ID then we will send an error basis please provider buy it is ready ok so let's let me change this so if user doesn't exist type if invalid user ID provided validation error melodies are provided validation error okay so let me provide a user ID 1 and the status code will be 4 under that's okay so yeah so I think this will be same because we will going to be providing an invalid ID it can be any ID so right now one doesn't exist in the database so it will be an valid ID it status done so we'll call the delete API once again and we'll send the status was equal to 400 of their user ID doesn't exist I think the only thing in the both test cases which will going to be changed is this the error message so instead of you have to provide a user ID it will be please provide user okay so let try to run this test and the two tests are passing the previous test bus both of the new tests are failing so that is because if there is a user ID we are not checking it into database or anything which is retaining a 200 which is not what we wanted we wanted 400 if we are passing the car invalid ID and also we want to check the error message but we are not sending an error message right now so that is also something that we have to do so now we have to basically find if the user exists in our database or not so let's do let's do that okay so now I'm going to do our wait so let me do it in a try-catch basically so I'm just going to do this Const my card equal to I think I have some user model here already I already created a user model if you want to see it it's here so inside the model folder I have like this user schema and I have already created a model of which I can use to search create or delete any user and I exported it and I imported it here and then I'm using it so I'm just going to e find the user by ID user dot find ID and then I'm going to provide the ID which is user ID here and this because we are using a single weight so rather than using dot then I'm just going to wait and see if I got any record what happened so I'm just doing this and if there is another it will go to catch inside catch I just okay let's see how this works okay says user is not defined because it is not its user model now we have once again going to hit the AP and you can see Scott's object ID field for value 1 at the path ID from model user don't you because this is not on the object ID okay so how we going to solve this this kind of problems are very simple so the problem that we are facing as a because this ID is not a valid object ID the user ID which Mongoose uses so it's throwing error that it can't be converted into a object ID so to and this is a really good case so for example if some user is providing like invalid user ID for example like this like 1 and everything we have we don't want our server to crash basically so we can also look for this kind of error for this kind of looking for this kind of error well we have to check for the error dot name so when the our code feel I can we can check for the peridot names so let's run this and when we run this hope we get the cast iron side the peridot Namath's I can soul the whole error you can see the whole error object also so inside you can see the message the name and everything but we this name is unique always far to there so we can use this so we can say if our dot name is equals to cast error then we can return the response as 400 and we can say provide a valid user ID I T because it makes sense right because the the user ID provided by us was like this integer like a single integer and it can't be casted into a valid DB user ID we are returning that this I'd Iike ID is not a valid user ID and we are sending the status is 400 and also sending the tyrannous let's see let's run our test and see if it works okay so you can see three is passing three tests are passing means the status code test is passing but the the error message test is not passing because we are like sending a different error message to let me fix that please provide a valid user let me copy this and please - okay so now if we try to run all of our tests got pass so let me summarize it once again so for example with this API with user ID 1 and what happens with what happens here is so I try to run the we try to find the user in the database but because the it is not a valid user ID we got into an error we check if it is a cast error and if it is a cast error that means it's not a valid user ID so we are sending another message this is one case but there is also another case that the ID can be valid so it can be a valid format but it doesn't necessarily mean that it should exist in the database let me give you an example okay so I have this valid format MongoDB ID but it's it doesn't exist in our database so I'll just put it here and let's see what happens and if I do an time test you can see two tests are passing two tests are failing because the reason for our test to fail our last two tests to fail is because the ID that we provided was a valid format ID so this catch never run and instead of that just 200 status code is getting returned so we also have to check if the format of the ID is valid but we also have to check if it is it exists in our database or not so we already found the record so we can put like a very simple check here if with God so if there is no record if not record then we can just do you can do something like this written response just status 400 JSON please provided user ID that is correct so what we are doing we are trying to find a user by ID and because that user doesn't exist in our database so the record is null and if the record is now you're just sending their sponsor status to 400 and then we are also showing that please provider while it is riding okay and also let's just put this here in the ads so if the record ID doesn't exist then we'll just go in to sender 400 instead and if it exists we'll just going to send 200 and just for now and let's turn these and you can see all the tests are passing just again once again some rice so what we are doing we are sending a valid down MongoDB format ID and so we get that a user ID and we find according to that user ID we are finding a user if that user exists or not if not if it does not exist then we are sending like an error and asking the user to provide a valid as a valid ID and effort exists then we are just sending the so I think that is it for the second tuskys text second test case is passing that is working fine just remain with this last case so let's just create it okay so our last case is if there is a valid ID then I pay should return a message versus that user I didn't get a successful let's create our last test so I'm going to copy and paste this so it will be the same but now we will be also testing this message inside one API the reason for that is because we can't delete one user multiple time so if we do like to request for example one for the status and one for the content then we are deleting the to AP's deleting the two users and we can do that because once this API basically had the user delay ID to user will got digital from the database and for the second time our IP will fail at pings and all let's also change the name for this whole you can do like status content because we are checking the status and content together in this okay and then we have the testing URL user user ID delete that is because we want so we have a user ID and then we do it status and content done request or delete then we basically pass the response body and check if the status code is 200 or the body dot message to equal is equal to user is successfully if both of these conditions are met then the test will it pass okay great okay so let's try to run this and you see this is for failing so this is now treated as one test because there is only one eight block so it is test it is getting such as one so that is okay so it says expected for near to equal 200 this is happening because this kind of an arbitrary user ID which doesn't exist now database so it's probably getting like a four hundred that you i user have to provide a valid user ID so we'll do that will change it but let's firstly create write our code here to actually delete our user from the database so so delete our user from database I'm going to use Mongoose find by ID and remove method so like this user and the response is good then we going to do this status the status should be 200 and the message will be user deleted successfully and forget okay so think we are good to go here so if the ID is vanity with your ID so we just put it in fine by ID and remove we get these we remove it and if everything goes fine we just return the status 200 and then we also have a Geo song here the messages you deleted so now try it let's try out with a valid user ID so let me create a user yeah okay so this is when it is ready you can see if I do db2 user defined I got this user ID so now I can put it here and let's see if it our test box and you can as you can see it gets pass and if I come here and you can see now it doesn't exist so our user is deleted if I try to run it one more time it will not work because that user ID doesn't exist in our database so guys um this is pretty much it to some rise of what we did today is this will be written three test cases and according to that we created a delete user API which is working perfectly fine one thing I really love about test cases that I don't have to use postman or another API tester to test my ep's I can use my test cases to test my EP and that works really fine so what I am going to put this code on github so you can now follow along the video tutorial and yeah okay so this is it for today I hope you really liked this video and if you have any kind of questions or when kind of drought you can always reach out to me and yeah don't forget to share this video like this video and subscribe to our a craft channel we are creating a lot of content related software development I hope you really love what we are creating so yeah and I see you on the flip side
Info
Channel: Recraft Relic
Views: 4,094
Rating: 4.8461537 out of 5
Keywords: nodejs, javascript, unit test cases, tdd, express, api, github
Id: -PuUX9EFGGA
Channel Id: undefined
Length: 48min 2sec (2882 seconds)
Published: Tue Oct 22 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.