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! ua-cam.com/video/v77fjkKQTH0/v-deo.html
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!
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 ?
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.
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.
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!
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
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.
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😊
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?
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
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
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 :)
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!!
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
Thank you Mr Ziggy! I recommend you check out this video which is how I prefer to handle Axios mocking these days: ua-cam.com/video/v77fjkKQTH0/v-deo.html
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
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.
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?
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.
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!
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..
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?
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.
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?
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: ua-cam.com/video/v77fjkKQTH0/v-deo.html
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?
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.
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"
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.
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?
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.
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.
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
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. 😌
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!!
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.
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!
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
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
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: ua-cam.com/users/leighenespanol
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.
@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?
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! ua-cam.com/video/v77fjkKQTH0/v-deo.html
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!
Thanks Thisis atest! I appreciate it
Agreed!
I really like the format of this video. I like how, at the end you go over everything that you did again.
Sweet! Glad you enjoyed it, loopduplicate! Thanks for watching.
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 ?
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.
Thank you so much :) I'll try to do more on testing!
You should make paid courses one day, I’d buy it after watching this video, extremely easy to follow, well done man
Thanks so much, Anton! I've got a ton of free videos planned this year :)
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.
Awesome! Thanks Matthew! :)
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!
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!
Thank you! That's awesome :) Tell your friends, tell your parents, tell your boss, tell your kids.
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
Hey Vivek! This is something that Jest does automatically... __mocks__ is a special folder it looks for and uses when available.
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.
Thanks Ben, appreciate it!
Nicely explained. After watching so many videos, this is one of the finest with proper detail. kudos
Thank you Rubin! I recommend checking out this video next: ua-cam.com/video/v77fjkKQTH0/v-deo.html
@@leighhalliday will do for sure
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😊
Definitely check out "mock service worker" too!
Thank you for making this video. I finally know how to mock api after watched this video!
Really good video, explains in a straight and practical way
Thank you Léo!! Glad you enjoyed it :)
This is exactly what I have been looking for! Top quality video, and thank you for saving me from a migrane of test issues :)
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 :)
It has now been done :)
A very good introductory video on mocking axios in jest. thanks a ton.
Thanks Sam, I recently did a few videos on mocking fetch if you are interested :)
@@leighhalliday I did watch them and have through few of your other videos too. Very good and professional content. Worth a sub. Thanks again.
2021, your tutorial is still the best!
You, Sir, are a savior! o/
Glad you're enjoying them, thank you!!
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?
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
So awesome step-by-step course, looking forward for your more course about JavaScript.
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 :)
Hi Leigh, your video help a lot and clearer the subject. Congratulations.
Thank you for the congratulations! Glad you enjoyed it :)
won't work for me axios insde __mokcs__ defaults always to the original module :(
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
This is fantastic. Thank you! Mock functions finally make sense to me!
Woohoo!!
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 :)
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!!
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
Muchas gracias era justo lo que necesitaba, que bueno que tambien tengas un canal en español.
Thank you Mr Ziggy! I recommend you check out this video which is how I prefer to handle Axios mocking these days: ua-cam.com/video/v77fjkKQTH0/v-deo.html
You have very well explained how to mock service.
Thank you, Abhishek!
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
how comes when we import the axios it directly imports the mocked one? I want to understand the flow?
could you show how to setup the __mocks__/axios.js to handle multiple endpoints and payloads ?
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.
Thanks. Exactly what I was looking for.
Liked. Subed. Looking forward for new episodes.
Sweet!! Thanks :) I'm thinking about my next one now... probably something with GraphQL.
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?
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.
@@leighhalliday Cool
How would you make a post mock call...because those need like parameters or something, right?
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!
this video did my day happier
Thank you Vitor!
Thanks buddy! Great video! Great explanation!
You're very welcome! Check out this video if you would like a good follow-up: ua-cam.com/video/v77fjkKQTH0/v-deo.html
so gooood! Have you learned more since then? Do you have more videos like this?
Yes! I actually prefer this approach now rather than mocking Axios: ua-cam.com/video/v77fjkKQTH0/v-deo.html
You saved me, THANKS !
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..
I'm not sure Subhranshu! Maybe someone else watching the video will know :D
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?
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.
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?
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: ua-cam.com/video/v77fjkKQTH0/v-deo.html
@@leighhalliday I get you, thanks for the response I found that video very informative too, subscribed :D
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?
I think it's automatically built into jest to look inside of that folder.
Great Video , keep it up. can you please share what font are you using ?
Hey! You can check out what I am using here: uses.tools/leighhalliday
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.
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.
What about negative test case when we receive e.g. 404 Http status code? Could you cover such case? Anyway good movie!
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.
Good format of this video! Like)
Thanks Nosko! Glad you enjoyed it :)
Great tutorial easy to understand, terimakasih
You're very welcome, Restu!
really nice explanation !
Thank you very much, Igor!
Great tutorial. Thank you!
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"
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.
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?
I believe it is, but to be sure, I recommend reading through the docs here: jestjs.io/docs/en/manual-mocks
Excellent video. Thanks!
Thanks, Ross!!
multiple mock.resolved are not running why?
Hey Taslim! Honestly not sure why!
@@leighhalliday Hey Leigh! Thanks for the reply man. It was my mistake, I fixed it😀
Very good video, nicely explained
Thank you Wojciech! Glad you enjoyed it! Please subscribe if you haven't yet!
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.
I would maybe check out MSW (mock service worker) ua-cam.com/video/v77fjkKQTH0/v-deo.html because I've had a bit more luck with it... I prefer it!
Excellent work!
Thank you Mrtech!
Perfect explanation, thank you!
Thanks Kreator!!
this was awesome, thank you very much!
Thanks, Shiraz!!
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.
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.
wondering why not using .mockResolvedValue or .mockResolvedValueOnce?
Not sure! Are they better?
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
Great explanation! Thanks
But I have a question why do we mock axios whats the reason?
Its was really a great help. I have one issue, though it not working as expected.
Thanks Swapana! Tell us more! Or share a codepen so we can take a look.
can you please update your theme extension
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. 😌
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!!
axios under __mocks__ won't work for me :/
Very helpful, thank you!
Very practical!
Thanks, Alex!!
very useful, thank you :)
Thanks very much Mechraoui!
Thank you very much sir. :)
To my favorites asap!!!
Thank you, G!!! :)
thank you thank you thank you man
at 0:38 you said that axios (a library) could get angry? There is not axios servers, it is just a library right?
Pretty sure he meant the api provider (unsplash), not axios 👍
which theme are you using?
One Monokai
It would be great if you share the github repo for this tutorial
I believe I link to it in my article here: www.leighhalliday.com/mocking-axios-in-jest-testing-async-functions
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.
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!
Dont mock what you dont own
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
Hi, Leigh, do you have the source code in github?
Yup! There are links to the final source code here: www.leighhalliday.com/mocking-axios-in-jest-testing-async-functions
Thank you!
The pleasure is all mine :)
Thank you
Thanks for watching, Igor!
Hello please could you help me
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
@@leighhalliday i already send you a tweet
thanks for helping me
Just replied on twitter :)
Why not just use moxios?
moxios.install(API);
moxios.stubRequest(url, { response: {})
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.
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' }))
);
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
@@leighhalliday thank so much i really appreciate it
With typescript dont work
I think I would check out an alternative approach like mock service worker
good
Thanks :)
y esa camiseta? jajajaja soy del verde soy feliz... Colombia
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: ua-cam.com/users/leighenespanol
Dont mock what you dont own
why?
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.
@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?
@Aleksandr there are better blog posts that can explain you more about this by google search for “dont mock what you dont own”
Nice video, but using axios library doesn't you are "hitting axios servers". lel
Thanks TDDIRLAF! What do you mean?