Mocking Axios in Jest + Testing Async Functions

  Рет қаралды 82,795

Leigh Halliday

Leigh Halliday

6 жыл бұрын

Article and source code here: www.leighhalliday.com/mocking...
In this video we'll look at a function that makes an HTTP request using the axios library to the Unsplash API and figure out how we can test it using a fake/mock version of axios to avoid performing real HTTP requests. We will be using Jest and some mocking functionality that it provides.

Пікірлер: 185
@leighhalliday
@leighhalliday 3 жыл бұрын
I made this video a while ago, and I actually have an updated video showing my preferred way of handling Axios/Fetch requests while testing. Check it out! kzbin.info/www/bejne/rGial52hgLaHfpI
@gxd4b1
@gxd4b1 5 жыл бұрын
This was great. I really liked that you didnt just jump to the perfect solution straight away. By that I mean you did something logical, then ran the test, something would go wrong, you would explain why it went wrong, then take the next step to fix it and move on. So many tuts just show 'Oh you do this, and this, and then everything works.' - Your step by step walk through, where you actually said 'hey at this point you'll get this error, but this is why and this is what we do to fix it' was great!
@leighhalliday
@leighhalliday 5 жыл бұрын
Thanks Thisis atest! I appreciate it
@dawid_dahl
@dawid_dahl 3 жыл бұрын
Agreed!
@cupoflife5378
@cupoflife5378 2 жыл бұрын
At last one of the best tutorial on unit testing. Thanks a lot for the time and effort you have put into this. Anything more related to unit testing will be appreciated.
@leighhalliday
@leighhalliday 2 жыл бұрын
Thank you so much :) I'll try to do more on testing!
@loopduplicate
@loopduplicate 4 жыл бұрын
I really like the format of this video. I like how, at the end you go over everything that you did again.
@leighhalliday
@leighhalliday 4 жыл бұрын
Sweet! Glad you enjoyed it, loopduplicate! Thanks for watching.
@aidarousjibril6323
@aidarousjibril6323 3 жыл бұрын
Leigh Halliday hey Leigh, how to test Mern Stack todo list app please, if you comparing items being fetched and rendered in component should be same number as items stored in DB please ?
@leonardokala
@leonardokala 2 жыл бұрын
This was super helpful! I was really confused about mocks. Your video helped me to understand them better and continue with my tests. Thank you!
@antonvoltchok7794
@antonvoltchok7794 5 жыл бұрын
You should make paid courses one day, I’d buy it after watching this video, extremely easy to follow, well done man
@leighhalliday
@leighhalliday 5 жыл бұрын
Thanks so much, Anton! I've got a ton of free videos planned this year :)
@kilgarenone
@kilgarenone 5 жыл бұрын
Whoa dude...you saved my life. I'm new to Jest, and have read bits and pieces about how to mock axios, but nothing clicked until I watched this video! I had tried like axios-mock-adapter, moxios, but nothing worked cuz I was stuck in the axios.create undefined error. This video really explains and sum up very well that I realized I didn't actually need all that shits cuz I understand how Jest itself works now! Thank you so much. Keep it up. Subbed!
@leighhalliday
@leighhalliday 5 жыл бұрын
Thank you! That's awesome :) Tell your friends, tell your parents, tell your boss, tell your kids.
@painslay
@painslay 6 жыл бұрын
This is exactly what I have been looking for! Top quality video, and thank you for saving me from a migrane of test issues :)
@leighhalliday
@leighhalliday 6 жыл бұрын
Yesssss! That's why I make these videos! Please subscribe if you haven't already... my goal is to keep producing a video per week :)
@painslay
@painslay 6 жыл бұрын
It has now been done :)
@satsuyakoukousseiga
@satsuyakoukousseiga 5 жыл бұрын
Thank you for making this video. I finally know how to mock api after watched this video!
@benpugh448
@benpugh448 6 жыл бұрын
excellent video. been slamming my head against the wall trying to test some of my axios helper functions. appreciate the explanation / motivation for each piece of code and REALLY appreciate the recap at the end. thank you.
@leighhalliday
@leighhalliday 6 жыл бұрын
Thanks Ben, appreciate it!
@jvfaeldon
@jvfaeldon 2 жыл бұрын
Thanks for the video. Finally! After several attempts of understanding and reading the easier step by step process of implementing this. i can able to run and perform autotesting now. I just subscribed to your channel now because of this. Looking forward for more tutorial videos from you😊
@leighhalliday
@leighhalliday 2 жыл бұрын
Definitely check out "mock service worker" too!
@rubinbhandari124
@rubinbhandari124 3 жыл бұрын
Nicely explained. After watching so many videos, this is one of the finest with proper detail. kudos
@leighhalliday
@leighhalliday 3 жыл бұрын
Thank you Rubin! I recommend checking out this video next: kzbin.info/www/bejne/rGial52hgLaHfpI
@rubinbhandari124
@rubinbhandari124 3 жыл бұрын
@@leighhalliday will do for sure
@matthewbridges3147
@matthewbridges3147 6 жыл бұрын
I've been tying myself in knots trying to write mocks that take a meta argument which determines the Spy. Knew it was a code smell, just too tired to find the simple solution. Thank you for this, it was was super helpful.
@leighhalliday
@leighhalliday 6 жыл бұрын
Awesome! Thanks Matthew! :)
@henriquebock
@henriquebock 5 жыл бұрын
Hi Leigh, your video help a lot and clearer the subject. Congratulations.
@leighhalliday
@leighhalliday 5 жыл бұрын
Thank you for the congratulations! Glad you enjoyed it :)
@dennisge9622
@dennisge9622 4 жыл бұрын
So awesome step-by-step course, looking forward for your more course about JavaScript.
@leighhalliday
@leighhalliday 4 жыл бұрын
Thanks ge Dennis!! Stay tuned, more on the way! There's a large backlog of videos and articles on my website to check out too :)
@leoandrade3093
@leoandrade3093 3 жыл бұрын
Really good video, explains in a straight and practical way
@leighhalliday
@leighhalliday 3 жыл бұрын
Thank you Léo!! Glad you enjoyed it :)
@Sam-sv9oi
@Sam-sv9oi 4 жыл бұрын
A very good introductory video on mocking axios in jest. thanks a ton.
@leighhalliday
@leighhalliday 4 жыл бұрын
Thanks Sam, I recently did a few videos on mocking fetch if you are interested :)
@Sam-sv9oi
@Sam-sv9oi 4 жыл бұрын
@@leighhalliday I did watch them and have through few of your other videos too. Very good and professional content. Worth a sub. Thanks again.
@tanishaaberdeen1778
@tanishaaberdeen1778 5 жыл бұрын
This is fantastic. Thank you! Mock functions finally make sense to me!
@leighhalliday
@leighhalliday 5 жыл бұрын
Woohoo!!
@noursidaoui8278
@noursidaoui8278 3 жыл бұрын
2021, your tutorial is still the best! You, Sir, are a savior! o/
@leighhalliday
@leighhalliday 3 жыл бұрын
Glad you're enjoying them, thank you!!
@varan22
@varan22 6 жыл бұрын
Thanks. Exactly what I was looking for. Liked. Subed. Looking forward for new episodes.
@leighhalliday
@leighhalliday 6 жыл бұрын
Sweet!! Thanks :) I'm thinking about my next one now... probably something with GraphQL.
@bssushmitha6534
@bssushmitha6534 4 жыл бұрын
The explanation was just awesome. I looked at so many other examples online for mocking axios and testing actions, but the explanaton was not that clear. But, your video explains it perfectly. I have a request for you to make a course for unit testing [in either Redux or Vuex ]. Finally, Thank You so much for making it clear :)
@leighhalliday
@leighhalliday 4 жыл бұрын
Thanks so much :) I'm glad the video was able to help!! Being transparent, right now I don't have those videos in my pipeline (because I don't know Vue yet and haven't been using Redux very much lately), but I'll do my best to keep producing videos!!
@pannihto7588
@pannihto7588 2 жыл бұрын
Great tutorial. Thank you!
@abhishekshukla2745
@abhishekshukla2745 5 жыл бұрын
You have very well explained how to mock service.
@leighhalliday
@leighhalliday 5 жыл бұрын
Thank you, Abhishek!
@islammurtazaev4891
@islammurtazaev4891 5 жыл бұрын
Great explanation! Thanks
@ziggys.9768
@ziggys.9768 3 жыл бұрын
Muchas gracias era justo lo que necesitaba, que bueno que tambien tengas un canal en español.
@leighhalliday
@leighhalliday 3 жыл бұрын
Thank you Mr Ziggy! I recommend you check out this video which is how I prefer to handle Axios mocking these days: kzbin.info/www/bejne/rGial52hgLaHfpI
@vitorgonzaga9985
@vitorgonzaga9985 2 жыл бұрын
this video did my day happier
@leighhalliday
@leighhalliday 2 жыл бұрын
Thank you Vitor!
@user-oy4kf5wr8l
@user-oy4kf5wr8l 3 жыл бұрын
Thanks buddy! Great video! Great explanation!
@leighhalliday
@leighhalliday 3 жыл бұрын
You're very welcome! Check out this video if you would like a good follow-up: kzbin.info/www/bejne/rGial52hgLaHfpI
@kreator1545
@kreator1545 5 жыл бұрын
Perfect explanation, thank you!
@leighhalliday
@leighhalliday 5 жыл бұрын
Thanks Kreator!!
@iantunbridge7190
@iantunbridge7190 4 жыл бұрын
I love the style of your video - clear, thorough and practical. I have a question about how the Mock behavior is used instead of the actual implementation in the 'axios' namespace. In other words, how does `import mockAxios from "axios"` know to use the module exported from `./__mocks__/axios.js` instead of `./node_modules/axios/index.js` (or wherever the export is defined)? And furthermore, why do you need to use the `.mockImplementationOnce()` instead of configuring the return value for the mock you already created (`./__mocks__/axios.js`)? Am I missing something entirely?
@leighhalliday
@leighhalliday 4 жыл бұрын
Hey Ian! Nope you're not missing something... it's sort of magical! But it is actually functionality provided by Jest... it knows to look into the __mocks__ folder to see if that package exists there. Details here: jestjs.io/docs/en/manual-mocks.html
@w.n.4711
@w.n.4711 4 жыл бұрын
Good format of this video! Like)
@leighhalliday
@leighhalliday 4 жыл бұрын
Thanks Nosko! Glad you enjoyed it :)
@HaniYahya9
@HaniYahya9 5 жыл бұрын
Very helpful, thank you!
@youssefmuhamad3213
@youssefmuhamad3213 5 жыл бұрын
You saved me, THANKS !
@rosscarrick
@rosscarrick 5 жыл бұрын
Excellent video. Thanks!
@leighhalliday
@leighhalliday 5 жыл бұрын
Thanks, Ross!!
@MrMandrivo
@MrMandrivo 6 жыл бұрын
Very good video, nicely explained
@leighhalliday
@leighhalliday 6 жыл бұрын
Thank you Wojciech! Glad you enjoyed it! Please subscribe if you haven't yet!
@shiraz6867
@shiraz6867 4 жыл бұрын
this was awesome, thank you very much!
@leighhalliday
@leighhalliday 4 жыл бұрын
Thanks, Shiraz!!
@chauhanvivek27
@chauhanvivek27 5 жыл бұрын
Thank for the video .. but I don’t understand one thing ... when you create the axios.js file in __mocks__ folder . How our test file start calling the mock axios as we didn’t import that file anywhere till then
@leighhalliday
@leighhalliday 5 жыл бұрын
Hey Vivek! This is something that Jest does automatically... __mocks__ is a special folder it looks for and uses when available.
@uimarshall6012
@uimarshall6012 4 жыл бұрын
Excellent work!
@leighhalliday
@leighhalliday 4 жыл бұрын
Thank you Mrtech!
@gzull90
@gzull90 4 жыл бұрын
really nice explanation !
@leighhalliday
@leighhalliday 4 жыл бұрын
Thank you very much, Igor!
@alextorres8275
@alextorres8275 4 жыл бұрын
Very practical!
@leighhalliday
@leighhalliday 4 жыл бұрын
Thanks, Alex!!
@sagarbhingare3308
@sagarbhingare3308 2 жыл бұрын
I created axios instance in my class using axios.create and added intercptor for that to add headers and params. but now I cannot mock that instance of axios
@restuwahyusaputra7764
@restuwahyusaputra7764 3 жыл бұрын
Great tutorial easy to understand, terimakasih
@leighhalliday
@leighhalliday 3 жыл бұрын
You're very welcome, Restu!
@danielelmuneco1994
@danielelmuneco1994 4 жыл бұрын
Ey man, great video! Random question: does your shirt says 'Soy del verde soy feliz'? Hahaha, that is from a futbol club called 'Atlético Nacional' from Medellin, Colombia. How did you get that shirt? 😂😂 Greetings from Colombia, and thanks for the video again, it was awesome. 😌
@leighhalliday
@leighhalliday 4 жыл бұрын
Hey Daniel! I'm married to a paisa :) I've been to Medellin many times and have lived there for a short time... I love that city! Thanks for watching!!
@kylerebstock1487
@kylerebstock1487 3 жыл бұрын
so gooood! Have you learned more since then? Do you have more videos like this?
@leighhalliday
@leighhalliday 3 жыл бұрын
Yes! I actually prefer this approach now rather than mocking Axios: kzbin.info/www/bejne/rGial52hgLaHfpI
@saoussenslii7225
@saoussenslii7225 2 жыл бұрын
how comes when we import the axios it directly imports the mocked one? I want to understand the flow?
@jakub3412
@jakub3412 5 жыл бұрын
Thank you very much sir. :)
@petriandy
@petriandy Жыл бұрын
Hey, I wanted to follow along with the code for this video but the repo you linked in your blog doesn't have a 'services' folder. I tried both the links--am I missing something? edit: the 'finished' link just lands on the same branch, I could switch to the 'mocking-axios-finished' branch and see all your code & folders--thanks
@iamchu
@iamchu 3 жыл бұрын
Really handy video thanks! What I don't understand from a testing point of view when it comes to mock functions though, does it not defeat the purpose of testing your actual code? Like your test may pass but it requires you to mock the actual function, which is prone to human error, which to me seems like the point of testing?
@leighhalliday
@leighhalliday 3 жыл бұрын
Hey Iain! Thank you :) I agree, except when it comes to HTTP requests... you can't always talk to a real API when running tests, and if you did, it would make the tests quite a bit slower. I have actually changed my preferred approach though, and it is to intercept the HTTP request rather than mocking fetch... here's a video on it: kzbin.info/www/bejne/rGial52hgLaHfpI
@iamchu
@iamchu 3 жыл бұрын
@@leighhalliday I get you, thanks for the response I found that video very informative too, subscribed :D
@GerardoBelot
@GerardoBelot 5 жыл бұрын
To my favorites asap!!!
@leighhalliday
@leighhalliday 5 жыл бұрын
Thank you, G!!! :)
@mechraouizeineb3818
@mechraouizeineb3818 5 жыл бұрын
very useful, thank you :)
@leighhalliday
@leighhalliday 5 жыл бұрын
Thanks very much Mechraoui!
@tonyaltamura
@tonyaltamura 5 жыл бұрын
Thanks you! I don't get just one thing: to me it seems you've "mocked" axios response twice: the first time in __mocks__ dir (in which you kept null as result), the second time in the test itself using mockImplementationOnce(). Is there no better solution?
@leighhalliday
@leighhalliday 5 жыл бұрын
Hey Alfredo! The one from the _mocks_ dir gets used by default every time, but if I want to test some specific result, like a specific data response or producing an error, I can override it by using mockImplementationOnce() just for a single test.
@subhranshudas8862
@subhranshudas8862 6 жыл бұрын
Awesome video. To the point and insightful..Quick question- do you know how to mock private function or object of a module used in another module that is being tested using Babel-plugin-rewire..when I try I get __Rewire__is undefined..
@leighhalliday
@leighhalliday 6 жыл бұрын
I'm not sure Subhranshu! Maybe someone else watching the video will know :D
@happyoe398
@happyoe398 4 жыл бұрын
Great Video , keep it up. can you please share what font are you using ?
@leighhalliday
@leighhalliday 4 жыл бұрын
Hey! You can check out what I am using here: uses.tools/leighhalliday
@leriksenbendigo
@leriksenbendigo 5 жыл бұрын
could you show how to setup the __mocks__/axios.js to handle multiple endpoints and payloads ?
@leighhalliday
@leighhalliday 5 жыл бұрын
That sounds like a great idea. I'll try to plan something :) I actually think in this case you wouldn't do it in the __mocks__ directory, but you'd individually mock your Axios calls for each test to have more fine grained control over what happens.
@lucasa8710
@lucasa8710 2 жыл бұрын
thank you thank you thank you man
@heliomoonwave
@heliomoonwave 5 жыл бұрын
Awesome video, thanks. I don't understand how the test knows to import axios from your __mocks__ folder without pointing anything there. Am I missing something?
@leighhalliday
@leighhalliday 5 жыл бұрын
I think it's automatically built into jest to look inside of that folder.
@zebnat
@zebnat 5 жыл бұрын
i was confused at first, so we are not testing the returned values from that api but instead if its sending the correct object params to the api.
@leighhalliday
@leighhalliday 5 жыл бұрын
Correct. The reason I chose to do it this way is because what the API controls isn't something we control... as an external system we control what we send to it.
@willydavid_
@willydavid_ 3 жыл бұрын
because the mock is called the same as the axios library is it a requirement to take the methods? in our case the one of get that is called ours instead of the real one?
@leighhalliday
@leighhalliday 3 жыл бұрын
I believe it is, but to be sure, I recommend reading through the docs here: jestjs.io/docs/en/manual-mocks
@zhrgci
@zhrgci 4 жыл бұрын
How would you make a post mock call...because those need like parameters or something, right?
@leighhalliday
@leighhalliday 4 жыл бұрын
Well if you're mocking it, the params don't really matter since the request wouldn't be hitting your server. So I think as long as it responds with whatever your code is expecting, you're good to go!
@davidwu9104
@davidwu9104 5 жыл бұрын
what does it mean by Axios might get angry everytime we make http request to the server? and I have questions about why the last assertion about mockaxios.get().tobecallwith(...); the request did not use the url and the env variable why the test pass?
@leighhalliday
@leighhalliday 5 жыл бұрын
Hey Ping! - It's not that Axios will get angry, but the URL you are fetching every time you run your tests, they may get annoyed you are hitting their API frequently... the biggest problem though is just that your tests will be slow. - It looks like it is using the URL/ENV vars here: github.com/leighhalliday/easy-mobx-redux-comparison/blob/mocking-axios-finished/src/services/unsplash.js but the mocked library is just not performing the actual call.
@davidwu9104
@davidwu9104 5 жыл бұрын
@@leighhalliday Cool
@pelaoinfo
@pelaoinfo 2 жыл бұрын
won't work for me axios insde __mokcs__ defaults always to the original module :(
@MSanchez1197
@MSanchez1197 2 жыл бұрын
en __mocks__/axios.js, usando get: jest.fn() pareciera que lo omite, pero si se reemplaza por get: () => Promise.resolve() ya no lo omite y usa el mock module que definimos. No sé que cambió, que ya no se pueden usar jest.fn( ) en los mock modules que uno define
@igor_cojocaru
@igor_cojocaru 4 жыл бұрын
Thank you
@leighhalliday
@leighhalliday 4 жыл бұрын
Thanks for watching, Igor!
@amindhahri2542
@amindhahri2542 Жыл бұрын
But I have a question why do we mock axios whats the reason?
@rollyrodrigz5069
@rollyrodrigz5069 5 жыл бұрын
Really thankyou. I was a liitle confusing but now it is clear. Do you have a tutorial to mock a Class? For example. I have a react component, inside react i instance a Class "Cat". i want to test the React Component but Mock the Class "Cat"
@leighhalliday
@leighhalliday 5 жыл бұрын
Try to think of Cat in the same way as Axios, you can mock it in the same way. Alternatively you could maybe pass the instance of Cat in as a prop to the component... that way it is easier to test because you can pass a fake "Cat" prop when testing. This way you are "injecting the dependency", and can inject fake dependencies for testing.
@yasssh7835
@yasssh7835 4 жыл бұрын
Thank you!
@leighhalliday
@leighhalliday 4 жыл бұрын
The pleasure is all mine :)
@CamdenBloke
@CamdenBloke 3 жыл бұрын
is anyone else getting 'Cannot find module 'babel-preset-react-app'' ? I solved this by deleting node_modules and yarn.lock and reinstalling dependencies. Also, this relies on an older version of node so I am using the package 'n' to achieve that.
@leighhalliday
@leighhalliday 3 жыл бұрын
Shoot, time flies by quickly in JS land eh? In 1 year everything's out of date haha... the concepts I think are mostly the same, but you'll have to see what the latest packages are. I recommend using the video for inspiration, but then looking at the docs themselves.
@swapanathorat3510
@swapanathorat3510 4 жыл бұрын
Its was really a great help. I have one issue, though it not working as expected.
@leighhalliday
@leighhalliday 4 жыл бұрын
Thanks Swapana! Tell us more! Or share a codepen so we can take a look.
@adrianolsk
@adrianolsk 5 жыл бұрын
at 0:38 you said that axios (a library) could get angry? There is not axios servers, it is just a library right?
@sethlesky8721
@sethlesky8721 5 жыл бұрын
Pretty sure he meant the api provider (unsplash), not axios 👍
@rahulbawa6864
@rahulbawa6864 2 жыл бұрын
I don't understand how this mock got tied to the real axios function. I tried using the same way but it didn't work for me. :( Can you explain that.
@leighhalliday
@leighhalliday 2 жыл бұрын
I would maybe check out MSW (mock service worker) kzbin.info/www/bejne/rGial52hgLaHfpI because I've had a bit more luck with it... I prefer it!
@kornelj2651
@kornelj2651 3 жыл бұрын
What about negative test case when we receive e.g. 404 Http status code? Could you cover such case? Anyway good movie!
@leighhalliday
@leighhalliday 3 жыл бұрын
I think you can mock 404 responses as well.. give it a try!! Check out MSW (mock service worker), I did a video on it if you want to google it.
@pelaoinfo
@pelaoinfo 2 жыл бұрын
axios under __mocks__ won't work for me :/
@lakkannawalikar4639
@lakkannawalikar4639 4 жыл бұрын
which theme are you using?
@leighhalliday
@leighhalliday 4 жыл бұрын
One Monokai
@janumedia
@janumedia 5 жыл бұрын
wondering why not using .mockResolvedValue or .mockResolvedValueOnce?
@leighhalliday
@leighhalliday 5 жыл бұрын
Not sure! Are they better?
@janumedia
@janumedia 5 жыл бұрын
as axios return promise, instead using .mockImplementationOnce you can use .mockResolvedValueOnce, although both working fine, but shorter. And as jest has that built in method why not using it
@tastaslim
@tastaslim 3 жыл бұрын
multiple mock.resolved are not running why?
@leighhalliday
@leighhalliday 3 жыл бұрын
Hey Taslim! Honestly not sure why!
@tastaslim
@tastaslim 3 жыл бұрын
@@leighhalliday Hey Leigh! Thanks for the reply man. It was my mistake, I fixed it😀
@charitreddy1
@charitreddy1 4 жыл бұрын
Hey man! What a great video it was! My search for doing this has finally ended. But I got struck at mocking response status in a POST call. Can you help me with this? Thank You!!
@leighhalliday
@leighhalliday 4 жыл бұрын
Hey charit! Feel free to share a codepen of the issue you're having and myself or maybe someone else that seems the comment can try to lend a hand :) Thanks for watching and saying hi!
@charitreddy1
@charitreddy1 4 жыл бұрын
@@leighhalliday codepen.io/CharitReddy/pen/yLNRvmW?editors=0010 Here is the code pen link, with both the function and test code included.(Feel free to call me dumb if I was. :P) It's literally after this video I got a picture of how unit tests should be written properly. Thank you so much! Keep up the good work!!
@leighhalliday
@leighhalliday 4 жыл бұрын
Hey Charit! I think you want to try to do 2 things: 1) Trigger whatever is going to call the event handler... whether that be a form submission or clicking a button. I think I see that you are overriding the onSubmit of the form, maybe you want to allow that to happen if it is what will eventually call your axios function. 2) Let axios know to expect a post request and what to return as a response... maybe something like this: mockAxios.post.mockImplementationOnce(() => Promise.resolve({ data: { results: "all good" } }) );
@charitreddy1
@charitreddy1 4 жыл бұрын
@@leighhalliday Thank you bud :) Will try to resolve the issue now. Really great of you to take time for this!
@dinuedm
@dinuedm 3 жыл бұрын
can you please update your theme extension
@davidwu9104
@davidwu9104 5 жыл бұрын
Hi, Leigh, do you have the source code in github?
@leighhalliday
@leighhalliday 5 жыл бұрын
Yup! There are links to the final source code here: www.leighhalliday.com/mocking-axios-in-jest-testing-async-functions
@PetukTraveller
@PetukTraveller 5 жыл бұрын
It would be great if you share the github repo for this tutorial
@leighhalliday
@leighhalliday 5 жыл бұрын
I believe I link to it in my article here: www.leighhalliday.com/mocking-axios-in-jest-testing-async-functions
@germanapazaninaraque8378
@germanapazaninaraque8378 3 жыл бұрын
good
@leighhalliday
@leighhalliday 3 жыл бұрын
Thanks :)
@CoryTheSimmons
@CoryTheSimmons 6 жыл бұрын
Mocks seem like a terrible idea. How can one confirm whether or not Axios, or the API is still returning the same stuff if we're just hard-coding the data comparison? It seems no better than just taking a snapshot of something and doing a comparison on that. Maybe I'm missing something... :\ For instance, what if Unsplash changes their API? Tests still pass, but your production app is broken. Thank you though for the education! Super interested in Cypress right now if you're looking for vid ideas. 😁 Also kinda curious in Rails (api-only) + React + nice token auth workflow, if you're getting burnt out on strictly React stuff.
@leighhalliday
@leighhalliday 6 жыл бұрын
If you're a Rails dev, you probably know about the VCR gem which is what I typically use to take a snapshot of the HTTP request... but to be honest you're not really solving anything unless you are constantly invalidating the snapshots and re-creating them... because a 1 year old snapshot only tells you how the API was a year ago. I've heard of the approach of not committing snapshots, and having them expire on maybe a weekly basis... or having a flag you can pass when you run your tests to run them without snapshots but only do this every once in a while. Maybe this is a bad idea, but I'd honestly just say to trust the mock/snapshot until your code tells you otherwise. If you don't have proper error reporting on your production environment to catch and fix errors, you're in trouble anyway. Maybe the focus should be on making your code resilient to APIs that go down, isolating them and allowing the app to run with limited functionality until you can push a fix up. GET requests can use old/cached results, POST/PUT requests can be done in the background such in Sidekiq or whatever the JS equivalent is, and re-run the failed jobs once you push out a fix. Thanks for the suggestions :) I'll do my best!
@jaimesangcap6134
@jaimesangcap6134 5 жыл бұрын
Dont mock what you dont own
@philipperathe
@philipperathe 5 жыл бұрын
You should not test what you don't own, so you should not test Unsplash API. If they roll out breaking changes in their API, you are screwed just as everybody else. You must be confident that stable API do not bring breaking changes. Anyway if the API breaks, it would be reflected directly in production and your users will face the broken API long before you trigger your tests
@palomanias
@palomanias 4 жыл бұрын
i dont knos how to test it const linkValidate = (id, url) => new Promise( (resolve) => axios(url) .then( (res) => resolve({ id, status: res.status, statusText: res.statusText }) ) .catch(() => resolve({ id, status: 404, statusText: 'FAIL' })) );
@leighhalliday
@leighhalliday 4 жыл бұрын
Hola Yenifer! Gracias por escribir! I published a very small repo showing how to test both the positive (valid link) and negative (invalid link) scenarios... there are some details in the README about the 3 files you should pay attention to: github.com/leighhalliday/minimal-mocking-axios-demo
@palomanias
@palomanias 4 жыл бұрын
@@leighhalliday thank so much i really appreciate it
@krisorsmso5094
@krisorsmso5094 5 жыл бұрын
Why not just use moxios? moxios.install(API); moxios.stubRequest(url, { response: {})
@leighhalliday
@leighhalliday 5 жыл бұрын
Cause I didn't know it existed :) But it's good to know how to do it by hand anyway for when you have to.
@kenjimaeda2443
@kenjimaeda2443 2 жыл бұрын
With typescript dont work
@leighhalliday
@leighhalliday 2 жыл бұрын
I think I would check out an alternative approach like mock service worker
@palomanias
@palomanias 4 жыл бұрын
Hello please could you help me
@leighhalliday
@leighhalliday 4 жыл бұрын
Sure thing! Feel free to ask me on Twitter (and share the example you're struggling with)... I'll do my best to help out. twitter.com/leighchalliday
@palomanias
@palomanias 4 жыл бұрын
@@leighhalliday i already send you a tweet thanks for helping me
@leighhalliday
@leighhalliday 4 жыл бұрын
Just replied on twitter :)
@titandiaz
@titandiaz 4 жыл бұрын
y esa camiseta? jajajaja soy del verde soy feliz... Colombia
@leighhalliday
@leighhalliday 4 жыл бұрын
Ya tu lo sabes chico! Vamos mi verde! ps - I have a channel in Spanish if you're interested in "contenido de alta calidad en español" hehe: kzbin.info
@jimlynchcodes
@jimlynchcodes 4 жыл бұрын
Nice video, but using axios library doesn't you are "hitting axios servers". lel
@leighhalliday
@leighhalliday 4 жыл бұрын
Thanks TDDIRLAF! What do you mean?
@jaimesangcap6134
@jaimesangcap6134 5 жыл бұрын
Dont mock what you dont own
@aleksandrvoloshchenko1979
@aleksandrvoloshchenko1979 5 жыл бұрын
why?
@leighhalliday
@leighhalliday 5 жыл бұрын
I agree with you for the most part, Jaime... sometimes I prefer this approach to mocking things like Axios though rather than creating wrapper functions and mocking them instead... I'd rather deal with the potential issues I'd run into by having mocked Axios than having 10-15 tiny functions whose only purpose is to avoid mocking Axios directly.
@jaimesangcap6134
@jaimesangcap6134 5 жыл бұрын
@leigh I was thinking that wrapping axios will prevent me from changing test when my implementation changes. And I imagine using axios or any http lib is pervasive in codebase that you need to abstract it?
@jaimesangcap6134
@jaimesangcap6134 5 жыл бұрын
@Aleksandr there are better blog posts that can explain you more about this by google search for “dont mock what you dont own”
Intro to React Testing Library
13:33
Leigh Halliday
Рет қаралды 34 М.
Mocking Asynchronous Functions with Jest
21:50
Swashbuckling with Code
Рет қаралды 66 М.
FOOTBALL WITH PLAY BUTTONS ▶️❤️ #roadto100million
00:20
Celine Dept
Рет қаралды 21 МЛН
Countries Treat the Heart of Palestine #countryballs
00:13
CountryZ
Рет қаралды 23 МЛН
ВЫКИНУЛА МОЙ АЙФОН?? #shorts
00:33
Паша Осадчий
Рет қаралды 2,2 МЛН
Mocking a Database in Node with Jest
13:29
Sam Meech-Ward
Рет қаралды 63 М.
JavaScript Testing - Mocking Async Code
18:05
Academind
Рет қаралды 144 М.
Mock vs Spy in Testing with Jest: Which is Better?
25:12
Dev tips by MoHo
Рет қаралды 9 М.
React Testing Library - Testing a mock Axios request
15:22
Leigh Halliday
Рет қаралды 47 М.
Unit Tests and Test Doubles like Mocks, Stubs & Fakes
17:32
Cognitive Programmer
Рет қаралды 130 М.
Axios API for JavaScript: GET, POST, PUT and DELETE requests
12:15
OpenJavaScript
Рет қаралды 37 М.
How to Mock Fetch in Jest Manually
9:46
Leigh Halliday
Рет қаралды 38 М.
How to use Vitest with Jest-DOM and React Testing Library
12:19
EricWinkDev
Рет қаралды 30 М.
FOOTBALL WITH PLAY BUTTONS ▶️❤️ #roadto100million
00:20
Celine Dept
Рет қаралды 21 МЛН