How to Mock Fetch in Jest Manually

Sdílet
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...

Komentáře • 60

  • @andrewhulme1188
    @andrewhulme1188 Před 3 lety +8

    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)

  • @jesusgodinho3478
    @jesusgodinho3478 Před 3 lety +6

    Not all heroes wear capes, quite literally. I've been looking to carry out the exact same tests for my API. True legend !

    • @leighhalliday
      @leighhalliday  Před 3 lety

      Haha thanks! Check out my video on mock service worker, you’re going to love it!

  • @eestiprogrammeerija1244
    @eestiprogrammeerija1244 Před 2 lety +1

    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

  • @MrVisheshsingh
    @MrVisheshsingh Před 4 lety +2

    Thank you! Keeping my 👀 open for the upcoming videos

  • @dawid_dahl
    @dawid_dahl Před 4 lety +5

    Finally a good testing tutorial! Thank you!

    • @leighhalliday
      @leighhalliday  Před 4 lety +1

      Hey Dawid! Check out the video I just published about Mock Service Worker, I think you'll like it!

  • @takeshikriang
    @takeshikriang Před 3 lety

    This is really good Leigh. Thanks for sharing.

  • @dominikseljan3043
    @dominikseljan3043 Před 4 lety

    Great one Leigh! Can't wait to see other two videos.

    • @leighhalliday
      @leighhalliday  Před 4 lety +1

      Thanks Dominik!! One today another tomorrow :)

  • @abessesmahi4888
    @abessesmahi4888 Před 4 lety +1

    I'am so excited to see the upcoming videos on testing
    Thank so much sir.

    • @leighhalliday
      @leighhalliday  Před 4 lety +2

      Thanks Abesse! One today another tomorrow! :)

  • @TheDoctorVideos
    @TheDoctorVideos Před 4 lety +1

    Great video, really helped me understand how the global fetch and mocking works!

  • @ArtiomNeganov
    @ArtiomNeganov Před 2 lety

    Very clear explanation. Thank you!

  • @nicholassmith6412
    @nicholassmith6412 Před 2 lety

    Excellent video

  • @umhurram
    @umhurram Před rokem

    Thanks Leigh!

  • @nimatsergiu2942
    @nimatsergiu2942 Před 4 lety

    Thanks man this really helped me out ;)

  • @ahmedjumaah9727
    @ahmedjumaah9727 Před 3 lety

    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

  • @briandevs
    @briandevs Před 3 lety

    Thanks Master!

  • @davidobodo3605
    @davidobodo3605 Před 2 lety

    thanks a lot for this

  • @MageLink
    @MageLink Před rokem

    Dude, you rocks

  • @Ls-xb2bn
    @Ls-xb2bn Před rokem

    Ur a god. Thanks!!!! Really thanks. This was so usefull

  • @larube
    @larube Před 4 lety +1

    Another good video !

    • @leighhalliday
      @leighhalliday  Před 4 lety +2

      Thank you Amador :D I appreciate the support!

    • @larube
      @larube Před 4 lety

      @@leighhalliday You deserve it !

  • @average-user9
    @average-user9 Před 3 lety

    thanks!
    and, it would be cool to have a link to second video in the end, and so on)
    thanks anyway)

  • @ImranKhansilvake
    @ImranKhansilvake Před 4 lety

    soo good. thankyou very much

  • @akamfoad
    @akamfoad Před 3 lety

    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?

    • @leighhalliday
      @leighhalliday  Před 3 lety

      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?

  • @ibadshaikh2215
    @ibadshaikh2215 Před rokem

    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.

  • @sushmak3110
    @sushmak3110 Před 3 lety

    Hi Leigh, could you please guide how to mock sequalize ORM on sqlite db

    • @leighhalliday
      @leighhalliday  Před 3 lety

      Hey Sushma! Perhaps :D If it's something I run into in my development, I'll definitely do one.

  • @nikosspiropoulos8417
    @nikosspiropoulos8417 Před 2 lety +1

    the global function fetch now returns undefined when i assing jest.fn to the global object. ANY IDEAS/??????? thanks in advance

  • @MohieddineSaadeh
    @MohieddineSaadeh Před 2 lety

    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.

  • @pravinpoudel1307
    @pravinpoudel1307 Před 3 lety +1

    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?

  • @bindushree1037
    @bindushree1037 Před 2 lety

    Can you make a video on how to mock the post fetch request which connected to backend having url like localhost:8080 using jest

    • @leighhalliday
      @leighhalliday  Před 2 lety

      Hey! I would check out "mock service worker" for this sorta thing.

  • @SheryarShirazi
    @SheryarShirazi Před 3 lety

    I'm not getting intellisense like it/test in VSCode react anyone knows?

  • @chetanjain4616
    @chetanjain4616 Před 2 lety

    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?

  • @alanthomasgramont
    @alanthomasgramont Před 4 lety

    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__

    • @leighhalliday
      @leighhalliday  Před 4 lety

      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.

  • @stevereid636
    @stevereid636 Před 4 lety

    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?

    • @leighhalliday
      @leighhalliday  Před 4 lety +1

      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?

    • @stevereid636
      @stevereid636 Před 4 lety

      @@leighhalliday Thanks for the suggestion anyway 👍🏾

  • @rajat420420
    @rajat420420 Před 4 lety

    How to mock superagent?

    • @leighhalliday
      @leighhalliday  Před 4 lety

      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

  • @bigk9000
    @bigk9000 Před 3 lety

    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.

    • @leighhalliday
      @leighhalliday  Před 3 lety +1

      Hey King! Give this a try... it's my preferred way to do it now: czcams.com/video/v77fjkKQTH0/video.html

  • @DarrylHebbes
    @DarrylHebbes Před 4 lety

    part time forex trader?

    • @leighhalliday
      @leighhalliday  Před 4 lety +1

      Hehe nah, it's just hard to find a simple API to use in examples that doesn't require an API key :D