How to Mock Fetch in Jest Manually
Vložit
- čas přidán 27. 07. 2024
- This video covers how to test a function which makes an HTTP call with fetch, mocking it in Jest to avoid actual HTTP calls, covering both success and failure test cases.
Source code
github.com/leighhalliday/mock...
Article (Other videos here as well)
www.leighhalliday.com/mock-fe...
Jest mocks
jestjs.io/docs/en/es6-class-m...
Thanks for the video Leigh, very helpful
For anyone having issues where it returns undefined, I solved it by putting the 'global.fetch....' INSIDE the 'it' function (or in a beforeEach)
Thanks Andrew! Thanks for sharing how you solved the issue!
Thank you
Not all heroes wear capes, quite literally. I've been looking to carry out the exact same tests for my API. True legend !
Haha thanks! Check out my video on mock service worker, you’re going to love it!
THANK YOU SO MUCH MAN, you save a lot of time for me, i was googling this for 2 days with no certain answer, thanks
Thank you! Keeping my 👀 open for the upcoming videos
Coming tomorrow and Sunday :)
Finally a good testing tutorial! Thank you!
Hey Dawid! Check out the video I just published about Mock Service Worker, I think you'll like it!
This is really good Leigh. Thanks for sharing.
Great one Leigh! Can't wait to see other two videos.
Thanks Dominik!! One today another tomorrow :)
I'am so excited to see the upcoming videos on testing
Thank so much sir.
Thanks Abesse! One today another tomorrow! :)
Great video, really helped me understand how the global fetch and mocking works!
Awesome!! Happy it helped :)
Very clear explanation. Thank you!
Excellent video
Thanks Leigh!
Thanks man this really helped me out ;)
Glad I could help, Nimat! Thank you!
Hi Leigh, what if we have a react useState and want to pass the response to the state, how would we test this scenario ? Thanks
Thanks Master!
thanks a lot for this
Dude, you rocks
Ur a god. Thanks!!!! Really thanks. This was so usefull
Another good video !
Thank you Amador :D I appreciate the support!
@@leighhalliday You deserve it !
thanks!
and, it would be cool to have a link to second video in the end, and so on)
thanks anyway)
soo good. thankyou very much
Thanks Imran! I appreciate it!
thanks great video Leigh, but something is weird, global overriding don't work in my project when doing them outside it/test blocks, made with CRA as well as yours, I saw other projects also using global overriding outside it/test blocks and works well, it seems you guys tweaked something or what is wrong if not?
Hey Akam! Sorry... I am not really sure! Perhaps something has changed since the time this video was released... I believe I link to the source code... can you find anything there that might be why?
How to make sure that the fields coming from API response always remain unchanged.
Like if the returned object is { rates : {} } , how can I know that the rates key is always there.
Hi Leigh, could you please guide how to mock sequalize ORM on sqlite db
Hey Sushma! Perhaps :D If it's something I run into in my development, I'll definitely do one.
the global function fetch now returns undefined when i assing jest.fn to the global object. ANY IDEAS/??????? thanks in advance
Thanks for the video.. I followed the steps but funny enough reject failed my test even if I remove all expects.. Also I'm using NextJS and showing an error message on the screen which is not showing.. I know it is async to begin with, but I did await fetch in my code so basically the rendered HTML should have updated.. Anyways will dig into that.. Thought of sharing my experience.
Hello Leight on API request, i get error response of 'You have not supplied an API Access Key. [Required format: access_key=YOUR_ACCESS_KEY]' , is it just me or there is another way to access the API?
Can you make a video on how to mock the post fetch request which connected to backend having url like localhost:8080 using jest
Hey! I would check out "mock service worker" for this sorta thing.
I'm not getting intellisense like it/test in VSCode react anyone knows?
Hmmm... sorry, I'm not sure Sheryar!
Hey, sorry but I still don't get it, you are still fetching the API right? when , on line number 10, you call convert function it still fetches the API and return the results which lets say if I turn off my internet would result in a failed test right?
How do I mock a "service" which isn't using fetch? That service could just be a function call that is may be doing all sorts of things I don't want to test here.
import { computeData } from '../services/DataService'
I want to replace computeData for all my tests within the component that I'm testing. So my component is calling something like:
useEffect(() => {
setData(computerData(props.a, props.b));
},[props.a, props.b])
and when data is set, it renders a table or something. computerData isn't a math function or anything and every test might need a different computed result so I don't want to use __Mock__
Hey Alan! I would use a manual jest mock but then you can override it with jestjs.io/docs/en/mock-function-api#mockfnmockimplementationoncefn whenever you need it to do something specific for a single test.
I tried following using typescript.
I used this:
const globalAny: any = global;
globalAny.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ rates: { CAD: 1.42 } })
})
);
and it worked fine for a time, but when I got to the mockImplementationOnce() , typescript complained that "Property 'mockImplementationOnce' does not exist on type '(input: RequestInfo, init?: RequestInit | undefined) => Promise'."
Any ideas on how to resolve this?
Hey Steve! Sorry, I am not great with TypeScript... I personally don't know how, but maybe someone else does here? Maybe you can redefine the type of fetch to be a union of whatever type fetch normally has combined with the type of a fetch mock function?
@@leighhalliday Thanks for the suggestion anyway 👍🏾
How to mock superagent?
Hey Rajat! I think you could probably use the approach in this video which is less about mocking and more about intercepting HTTP requests, which would work for fetch/axios/superagent/etc... czcams.com/video/v77fjkKQTH0/video.html
Okay, no matter what I do, no matter which method I employ or what package I install, I cannot mock fetch. For whatever the reason, it's utterly impossible.
Hey King! Give this a try... it's my preferred way to do it now: czcams.com/video/v77fjkKQTH0/video.html
part time forex trader?
Hehe nah, it's just hard to find a simple API to use in examples that doesn't require an API key :D