Mocking Asynchronous Functions with Jest

Поделиться
HTML-код
  • Опубликовано: 19 июн 2024
  • Mocking is a fundamental skill in testing. It allows you to avoid testing parts of your code that are outside your control, or to get reliable return values from said code.
    00:00 - What we'll cover
    01:00 - Reviewing the project setup
    03:02 - Creating the test
    06:24 - Adding async await to pass test
    07:17 - Why mock an api request for unit tests
    08:32 - Adding jest mock for axios
    14:06 - Check if mock function has been called
    15:31 - Shorthand for mocking resolved promise value
    16:23 - Gotcha for mock state, and how to clear it each test
    18:24 - Alternate way of mocking within a test file
    20:50 - Wrap-up
    Repository for code example:
    github.com/Jimmydalecleveland...
    Blog Post:
    blog.jimmydc.com/mock-asynchr...
    Swapi Dev:
    swapi.dev/
    Follow Jimmy Cleveland's doings:
    twitter: / jimmydcleveland
    blog: blog.jimmydc.com/
    #jest #mock #async

Комментарии • 114

  • @sharonfitzpatrick5179
    @sharonfitzpatrick5179 2 года назад +49

    This is by far the best video I've found explaining mocking Jest

  • @saprone8885
    @saprone8885 2 года назад

    This is great and helped me a lot understanding async mocking and got it working in my own project! I am happy thanks for this :)

  • @CristianAndresNietoGarcia
    @CristianAndresNietoGarcia 2 года назад

    An excellent resource in my current journey in Unit testing

  • @kiberslav
    @kiberslav 2 года назад

    Very Useful video. Nice explaining 👏Thank you. Please keep it up with testing videos, this is gold.

  • @jonathanlinat
    @jonathanlinat 7 месяцев назад

    This was the most useful video I ever watched about mocking functions using Jest. You've made it pretty simple to understand the concept. Nice job Jimmy!

  • @mateuszszaowicz4373
    @mateuszszaowicz4373 9 месяцев назад +1

    This is the best video about mocking I have encountered, it really made me understand how it works. Big thanks to you sir!

  • @Andrans1
    @Andrans1 2 года назад +1

    Amazing tutorial, thanks for sharing your knowledge

  • @arfasaif6139
    @arfasaif6139 2 года назад

    one of the simplest and well-explained clean video of jest mocking so far! thanks!

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  2 года назад +1

      Thank you for the kind words. Always nice to hear that your efforts were appreciated.

  • @ShubhamKumar-mk6zb
    @ShubhamKumar-mk6zb 3 месяца назад

    I prefer blogs over videos, thankyou for making one and very understandable.

  • @ClareBeany
    @ClareBeany Год назад +2

    Thank you for being detailed and nuanced in your explanations! Really helps give context and bridge the learning curve that isn't always addressed in documentation. This is great!

  • @vikram87in
    @vikram87in 2 года назад

    The way you teach is fantastic! And yes, this is the best video on the topic.👏👏 Thank you so much

  • @aglowkeys
    @aglowkeys 2 года назад +3

    Thank you! This was so useful to me. Gonna be watching some more of your Jest videos now. :)

  • @imekachi
    @imekachi Год назад +5

    Thank you for taking us into traps and teaching us how to escape/fix them.
    Short, precise, and easy to understand, also with sections that you can jump around and quickly learn what you need. 👍 Amazing.

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  Год назад

      I appreciate the feedback and knowing that the effort was useful. Cheers!

  • @claudiobaumgartner2760
    @claudiobaumgartner2760 3 года назад +2

    Super interesting! Thx for the nice tutorial 🔥

  • @LeoMuzi
    @LeoMuzi Год назад +2

    Thank you so much! This is really useful to understand how mocking works under the hood, helps you thinking of what's going on to figure out issues with testing. Helped me a lot.

  • @bikizzle
    @bikizzle Год назад

    Thank you for this life saver video. This is great knowledge shared

  • @hhdev9954
    @hhdev9954 2 года назад +1

    Very good explained 💡, thank you Jimmy!😊

  • @matthieu1551
    @matthieu1551 3 года назад +2

    Very interesting. Thanks a lot 🤩

  • @j.ignacior.p.9481
    @j.ignacior.p.9481 5 месяцев назад

    Awesome video. Thank you very much.

  • @viridianite
    @viridianite Год назад +2

    Thank you so much, Jimmy! You're slowly demystifying testing JS code with Jest for me!

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  Год назад +1

      That's what I like to hear. Thank you for letting me know.

    • @viridianite
      @viridianite Год назад +1

      @@SwashbucklingwithCode You've a talent for pedagogy. Thanks for your video on asynchronous JS. I'm looking forward to your future videos :)
      I've a few topic suggestions:
      * REST API using express.js and some database library This could be a multiple parts series like your CI/CD series. You could show how you'd write the tests for it (e.g., unit tests, integration tests, and e2e tests), consume it with something like Axios, etc.
      * GraphQL API

  • @zacalves
    @zacalves 2 года назад +1

    great tutorial! thanks a lot for that!

  • @Bregylais
    @Bregylais Год назад

    Subscribed, liked, and alas commented. Beautifully explained!

  • @alfredmadere9030
    @alfredmadere9030 Год назад +1

    Great vid bruv. Make another about standard practices for mocking models and such

  • @petergoodey
    @petergoodey Год назад +1

    We have struggled with axios mocking on a complex React/Typescript project having only recently up-skilled. Best explainer!

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  Год назад

      Thank you for the kind words and I'm happy to hear your skills are improving.

  • @aashisharyal9704
    @aashisharyal9704 7 месяцев назад +1

    Amazing 👏👏 Thank you so much 💕

  • @dharmsingh6924
    @dharmsingh6924 2 года назад

    Nicely explained 👍

  • @tachylamurray9452
    @tachylamurray9452 Год назад +1

    God Bless you or whatever. I lost a whole day trying to figure out how to call my test async. So true how "it might not be so obvious to some" Thank You!

  • @Huey-ec1
    @Huey-ec1 15 дней назад

    Great explanation

  • @programandocomandersonsouza
    @programandocomandersonsouza 10 месяцев назад

    Excelent.
    Thank you so much.

  • @giachan4528
    @giachan4528 2 года назад +1

    this video is short and easy to understand, please make more videos for unit testing, it is helpful for a beginner like me. Thanks!

  • @johannyberg4988
    @johannyberg4988 3 года назад +1

    Good job!

  • @gordemn
    @gordemn Год назад

    Wow I was really struggling with this but got it to work thanks to your videos. Thank you js Jesus

  • @jimmymac601
    @jimmymac601 2 года назад +2

    I will personally hunt down anyone who downvotes this tutorial. Outstanding presentation.

  • @emmanuelsackey3026
    @emmanuelsackey3026 2 года назад +1

    Thank you. You earned a subscriber at "Sanity check" . Awesome bro.

  • @mubashirarif5792
    @mubashirarif5792 3 года назад

    Sir big fan...CodeStackr named you in his video on monday and I am since then loving your content....

  • @Alan.livingston
    @Alan.livingston Год назад +3

    Needs to be more stuff of this quality on the net. Most explanations are too simplistic and are aimed at people with no experience.

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  Год назад +1

      I agree, and thank you. I can empathize more now with the lack of intermediate videos because they are quite challenging to figure out how much explanation to put in without making the videos crazy long.

  • @shwackthenoobsac
    @shwackthenoobsac 2 года назад +1

    Thank you!

  • @santhoshraghavpidathala3701
    @santhoshraghavpidathala3701 3 года назад +4

    Please continue to teach jest and react testing library

  • @santhoshraghavpidathala3701
    @santhoshraghavpidathala3701 3 года назад

    Thanks a lot, I am about to ask jest and react testing library. Could you please teach promises with API not with settimeouut function

  • @adrianjason13
    @adrianjason13 2 года назад +2

    Helpful content, thanks! What VSCode extension are you using for intellisense/autocompleting Jest code?

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  2 года назад +1

      I believe that was shown in a previous video in this videos playlist, but it comes from installing @types/jest

  • @Menhoka
    @Menhoka 7 месяцев назад

    Awesome video! How can I mock the error case?

  • @Nurtylek
    @Nurtylek 3 года назад

    great!

  • @el.vilchez183
    @el.vilchez183 Год назад

    Thanks Jesus for teaching mocks :D

  • @OhReallyHuman
    @OhReallyHuman 8 месяцев назад

    "...test properly fails..." that line is hilarious and scary at the same time haha.

  • @harel2021
    @harel2021 3 года назад +1

    Awesome content, can you please upload more videos on jest and react-testing-library

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  3 года назад +3

      Unit Testing and Jest are likely the next series I'll be working on. I've had a few requests for testing-library, so I'll probably throw that in the mix.

  • @haralc
    @haralc 2 года назад +3

    Thank you Jesus for this tutorial! 🤣

  • @mohammedamin6859
    @mohammedamin6859 3 года назад +3

    awesome stuff man, can you create react-centric testing tutorials?

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  3 года назад

      I've been pondering on that for a little bit. I've had a few requests, but I'm not sure how much I'd be stepping on Kent C Dodds toes, since I use his library and he has a bunch of tutorials for it.
      Thanks for the request, I'll definitely be thinking on it.

  • @PrieyudhaAkaditaS
    @PrieyudhaAkaditaS 2 года назад +1

    Thankyou

  • @mahmoudnasser2158
    @mahmoudnasser2158 2 года назад +2

    What about if you have multiple gets to different endpoints and each return different information? How could you mock each api get separately to tell Jest “this is the data you should expect for api A but another data for API B”?

  • @suryapratap9915
    @suryapratap9915 Год назад +1

    @SwashbucklingwithCode Thank you so much for the in depth explanation. What if my function is having multiple axios calls and these axios calls are wrapped in another function called 'makeApiCall'.

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  Год назад +1

      If you have a function that abstracts all the fetching, it actually makes it easier to mock because you can just mock that module itself. Just make sure it is exported, and I usually put it in it's own file.

  • @y_thedreamer95
    @y_thedreamer95 Год назад +1

    which font do you use at WSL? it looks awesome!

  • @creative-commons-videos
    @creative-commons-videos 2 года назад +2

    Not always a response have success but sometimes it throws an Error too, so how can we mock the errors and handle it ?

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  2 года назад

      Lovely question. I'll likely do a part 2 of this video for error states and multiple endpoints.
      In the meantime, I'm sure other comment readers would love to here your (and others) answer after you take a stab at it.

  • @sameerizaj5458
    @sameerizaj5458 Год назад

    sir please answer me the thing is the api part i did understand the thing is i'm a backend dev right so i'll be testing the endPoint via your method right i'll not actually call the function since it'll be a endppoint and second thing is that what if i want to mock the function that interacts with mongdb and returns the promise so my question my team lead said you don't need to import the mock service file in which just mock the functions so that means that i''l allo do the same like just resolved the value that function return and also in my some spis i've very complex data like array which contains the objects and each might have the array nested so that's why i'm asking please help me i've deliverd the project tommorow

  • @sivaram7115
    @sivaram7115 Год назад

    what if we have 2 get api calls in the react component. How to return different values for both

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  Год назад

      I believe you can down some narrowing based on the endpoint path, but how I prefer to handle this is make a module that exports a bunch of api calls as functions. I name them based on what they do.
      This way, you can mock the entire function.

  • @oscareberle744
    @oscareberle744 2 года назад

    Thanks Jesus for this video! :)

  • @sauravthakur6261
    @sauravthakur6261 7 месяцев назад

    make a video on redis mock get set functions

  • @Emma-eb5zb
    @Emma-eb5zb 2 года назад

    How can I test a function that calls multiple other functions?

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  2 года назад +1

      You'd call it just the same as any other function. You likely should individually test those subfunctions as well.
      The only real issue is when there are side-effects happening with any function, and that's a situation where you either should mock or rewrite the function to not cause side-effects (depending on limitations).

  • @EulerAlvarenga1
    @EulerAlvarenga1 2 года назад

    I'm using typescript. When I call the real api the test works but when I call the mockImplementation it always returns undefined =/

    • @viridianite
      @viridianite Год назад

      You should be resolving the returned promise to some value. By default, Promise.resolve() resolves to undefined.

  • @aspirinemaga
    @aspirinemaga 2 года назад

    Very informative, but it seems won't work in my case for no reason

  • @Chavez3d
    @Chavez3d 2 года назад

    is lemmy kilmister your dad? also great video, sub'd!

  • @cla1814
    @cla1814 3 года назад

    you should post source code in the video description.

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  3 года назад

      In most videos I do, but this one was based off a blog post which has the required code. The complete test code is at the bottom, but I could see how it would be more convenient to have files to follow around.

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  3 года назад +1

      Added this in the description, thanks for letting me know:
      github.com/Jimmydalecleveland/jest-mock-async-example

    • @cla1814
      @cla1814 3 года назад

      @@SwashbucklingwithCode Always good idea to post code, even if at least github gist, that way If someone is coding alone can compare their code or save it for future reference.

  • @methmaaravinda5107
    @methmaaravinda5107 4 месяца назад

    oh jesus

  • @elsetiyawan
    @elsetiyawan 10 месяцев назад

    I feel like Jesus teach me testing.

  • @80Vikram
    @80Vikram Год назад

    Jesus is real and he loves TDD. Thanks for saving developers' lives US Jesus

  • @reasonforge9997
    @reasonforge9997 2 года назад +1

    Lots of mocking in this video...but it's all in Jest.

  • @hendra5604
    @hendra5604 3 года назад +2

    First ☝🏻😅

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  3 года назад

      You are indeed.

    • @hendra5604
      @hendra5604 3 года назад

      @@SwashbucklingwithCode What theme used there? Deep ocean?

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  3 года назад

      @@hendra5604 This is actually my own theme called Everset. marketplace.visualstudio.com/items?itemName=jimmydc.everset

    • @hendra5604
      @hendra5604 3 года назад +1

      @@SwashbucklingwithCode Perfect, many thanks. I just hated purple's around material theme. Created my own theme for personal use, had hard time to distinguish color between html, json, php, ts/js, py, yaml.

  • @erenyeager7465
    @erenyeager7465 10 месяцев назад

    Jesus

  • @yashkaliapiano
    @yashkaliapiano 9 месяцев назад

    Jesus teaching software testing

  • @shadev23
    @shadev23 Год назад

    Jesus ???? It's you ???

  • @serial_coder
    @serial_coder 2 месяца назад

    Jesus Christ

  • @jimlatsko4804
    @jimlatsko4804 3 года назад

    Can you please help with converting this to typescript? Specifically the line mockAxios.get.mockImplementation(() => Promise.resolve({data: {name: "Jimmy Jedi"}})); since mockImplementation generates the following compiler error: TS2339: Property 'mockImplementation' does not exist on type ' >(url: string, config?: AxiosRequestConfig) => Promise '.

    • @jimlatsko4804
      @jimlatsko4804 3 года назад

      With help from stackoverflow, got this working: here are some changes to consider for typescript:
      import axios from "axios";
      const mockAxiosGet = jest.spyOn(axios, 'get');
      mockAxiosGet.mockResolvedValue({ data: {name: 'Luke Skywalker'}});

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  3 года назад

      Have you already installed @types/jest ?

    • @jimlatsko4804
      @jimlatsko4804 3 года назад

      @@SwashbucklingwithCode yes.

    • @SwashbucklingwithCode
      @SwashbucklingwithCode  3 года назад

      @@jimlatsko4804 Hmmm I don't recall getting an error in TS for mock methods. You might have to set axios with teh `as` keyword to jest.Mock or something like that.

    • @EulerAlvarenga1
      @EulerAlvarenga1 2 года назад

      I had the same issue,
      With help from stackoverflow, got this working: here are some changes to consider for typescript:
      import axios from 'axios'; // import axios instead of mockAxios
      jest.mock("axios");
      const mockedAxios = axios as jest.Mocked // head up here, I changed the name of the var