Don't Mock Fetch (or Axios): Use Mock Service Worker and Test Like a User

แชร์
ฝัง
  • เผยแพร่เมื่อ 18 ม.ค. 2025

ความคิดเห็น • 140

  • @Sapphiamur
    @Sapphiamur ปีที่แล้ว

    This was a perfect explanation, I'm not even kidding! It's so hard to find good tutorials for testing in general and even several years later, you did a much better job than anyone/any tut I could find to this moment including (especially) the official docs! Thank you so much ❤! Seriously, when I tell you I struggled to grasp what is going on and what is supposed to be happening during mocks x'd.

  • @nicholasbernard2315
    @nicholasbernard2315 4 ปีที่แล้ว +9

    This was awesome! Thanks for all your hard work. I was literally explaining this to a friend of mine earlier today, but this video really clears up a number of concepts I didn't fully understand.

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Nice!! So glad it could help. I appreciate the support :)

  • @octoBadger
    @octoBadger 3 ปีที่แล้ว +1

    Just watched a different video on MSW - this is waaaay better. Very clear, concise explanations - great work, subscribed

  • @jerrydixon3862
    @jerrydixon3862 3 ปีที่แล้ว +1

    You literally just made my day with this video. Thanks for posting this, I'm going to test using this from now on!

  • @DhavalPateldp
    @DhavalPateldp 3 ปีที่แล้ว +4

    AMAZING!!! I've been mocking the imports and creating mock functions that return the result, it gets tricky when doing multiple calls with different bodies. This seems ideal and will try in future. THANK YOU.

    • @leighhalliday
      @leighhalliday  3 ปีที่แล้ว

      Thanks! Yea, I love this approach too!

  • @adeyemiadeyanju2247
    @adeyemiadeyanju2247 2 ปีที่แล้ว

    Thank you for the tutorial, i was just coming from rest testing libary docs and i was so confused with msw, but you cleared everything. earned a subcriber

  • @LeoMuzi
    @LeoMuzi 3 ปีที่แล้ว

    Thank you!! I usually don't comment much on youtube, but I was having a hard time at work while trying to understand how the heck my mock API would replace (or like I learned in this video, intercept) the real API call on my component while writing tests. This video helped me a lot!!

  • @muhammadsheharyar999
    @muhammadsheharyar999 4 ปีที่แล้ว +7

    This was great and came out at a perfect time. Thank you Leigh for another perfect video.

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Nice! Happy the video could help :)

  • @arishojaei
    @arishojaei 3 ปีที่แล้ว

    After watching many testing shits on youtube, this is the best content about testing. it was amazing. many thanks

  • @djthul
    @djthul 4 ปีที่แล้ว +1

    Thanks Leight! Another great video! Mocking has always mystified me, I would copy and paste something I found somewhere and hope it worked. I like the way this works and the way you set it up. It just seems to work in line with the actual application instead of faking it. Thanks for enlightening me, on to the refactoring!!

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Glad I could help a little, Dan!! Mocking is tricky for sure!

  • @Alan.livingston
    @Alan.livingston 2 ปีที่แล้ว

    This was super useful. Simple, clear, explanation. Fire.

  • @BivinityPeng
    @BivinityPeng 4 ปีที่แล้ว +2

    It's awesome for testing react app with this approach, THANK YOU!
    Really excited react-query for testing with msw haha

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      You're going to enjoy it! It's a nice combo.

    • @BivinityPeng
      @BivinityPeng 4 ปีที่แล้ว

      @@leighhalliday When I finished this video and I added msw into my app for testing with react-query, very clear! Thank you

  • @jacinyan3893
    @jacinyan3893 3 ปีที่แล้ว

    Clear as crystal as always

  • @Rolanditou
    @Rolanditou 3 ปีที่แล้ว

    Thanks for this Leigh !
    Another excellent video, your content is top of the food chain!

    • @leighhalliday
      @leighhalliday  3 ปีที่แล้ว +1

      Thank you so much Rolando!

  • @aspinwallx
    @aspinwallx 3 ปีที่แล้ว

    I got my job because of your videos. Thanks so much!!

    • @leighhalliday
      @leighhalliday  3 ปีที่แล้ว

      Congrats Alejandro!! I disagree though… you got it because of your hard work and putting in all those hours. Best of luck!!

  • @curiousprogrammer90
    @curiousprogrammer90 4 ปีที่แล้ว +4

    This makes testing React a breeze. Thank you!

  • @jaKERmEn100
    @jaKERmEn100 3 ปีที่แล้ว

    i love the way you explain everything. Thank you so much!

  • @omairnabiel9516
    @omairnabiel9516 3 ปีที่แล้ว

    This channel is Gold

  • @cyberpunk2042
    @cyberpunk2042 4 ปีที่แล้ว

    Great video Leigh! Keep them coming!

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      You got it! I'm aiming for 1 video per week :)

  • @arunh3
    @arunh3 3 ปีที่แล้ว

    Great videos on testing

  • @realconect
    @realconect 4 ปีที่แล้ว +1

    Another great video, thank you!

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Thanks Alan, I appreciate it!

  • @caiomar
    @caiomar 2 ปีที่แล้ว +1

    I watched the first one and now the second one, you are excellent at explaining all the important aspects and concepts. Real good work man! Would this work for axios request from inside of a useEffect the same way? I've been searching all over and it blows my mind that I can't find much about it.

    • @leighhalliday
      @leighhalliday  2 ปีที่แล้ว

      Yes! It should work the same.

  • @florianmartens9019
    @florianmartens9019 3 ปีที่แล้ว

    This vid is amazing 🧘🏽‍♂️ All explanations were just on point. This helped me a lot. I‘d love material on how to manage fixture data for a bigger project.

    • @leighhalliday
      @leighhalliday  3 ปีที่แล้ว

      Thanks Florian, glad you enjoyed it. I'd love that material too hehe :D

  • @9704923126
    @9704923126 4 ปีที่แล้ว

    Thanks for the video.. i really like the way you are explaining... easy to understand 👍

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว +1

      Thanks Siva, I appreciate the kind words!

    • @9704923126
      @9704923126 4 ปีที่แล้ว

      Leigh Halliday can you please make some more videos on algorithms and data structures..

  • @nazmulsisil
    @nazmulsisil 2 ปีที่แล้ว

    Awesome! 🙌

  • @kirankandula2779
    @kirankandula2779 3 ปีที่แล้ว

    Thanks for the video.

  • @caiofelixreis8970
    @caiofelixreis8970 4 ปีที่แล้ว

    Thanks man, you really helping us out here. Be Safe!

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Thanks Caio!! I appreciate it!

  • @JPBrothers_JayPatel_JeetPatel
    @JPBrothers_JayPatel_JeetPatel 2 ปีที่แล้ว

    Great learning !!! Thanks a lot🤘

  • @matibor
    @matibor 4 ปีที่แล้ว

    A.M.A.Z.I.N.G - this is what I needed. Thank you!

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว +1

      Nice! Glad I could help :)

  • @rorycawley
    @rorycawley 4 ปีที่แล้ว

    Leigh, this is excellent, thanks!

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Thanks Rory, glad you enjoyed it!

  • @lucasalmeida5277
    @lucasalmeida5277 3 ปีที่แล้ว

    You helped me a lot, thank you!

  • @Sindoku
    @Sindoku 3 ปีที่แล้ว

    great video, will you consider making a testing video on the nock package?

  • @christhomasism
    @christhomasism 4 ปีที่แล้ว

    Leigh your videos are so great man. Your videos were one of the resources that helped me get a job. Also Vercel rules. Do you use their serverless stuff at all?

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Hey Chris! Thank you so much... and big congrats on the job! For sure, both for personal projects just messing around, but also at FlipGive (work) we use Vercel for a few things :)

  • @herbertpimentel
    @herbertpimentel 4 ปีที่แล้ว

    awesome man! Thanks for this content

  • @annaiustus9445
    @annaiustus9445 3 ปีที่แล้ว

    Thank you a lot! you really save me

  • @Ls-xb2bn
    @Ls-xb2bn ปีที่แล้ว

    Really really usefull!!

  • @markopavic7012
    @markopavic7012 3 ปีที่แล้ว

    Great content.

  • @doug1727
    @doug1727 4 ปีที่แล้ว +1

    thats very nice, will give it a try! Is the slowness caused by Msw?

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Hey Douglas! No idea... sometimes it ran fast, sometimes slow... it might just be because it is in "watch" mode... or because I was recording a video at the same time... which makes my computer suffer a little bit.

  • @peterpistorius4466
    @peterpistorius4466 4 ปีที่แล้ว

    This was great, thank you!

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Thanks Peter, glad you enjoyed it! :)

  • @marvintrefzer8723
    @marvintrefzer8723 4 ปีที่แล้ว +2

    Thanks for another great video Leigh.
    Do you also test the actual round trips at any time to gain more confidence? If so: How do you call such tests and how do you handle the requests at the backend - especially POST/ PUT/ DELETE?

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Hmmm... good question, in Rails there is a library called VCR that makes a real call once and then caches the result for future test runs, I wonder if there is something similar for JS?
      Handling backend... I'm going to be working on more tutorials coming up which go over backend. Stay tuned!

    • @marvintrefzer8723
      @marvintrefzer8723 4 ปีที่แล้ว

      ​@@leighhalliday All right. Thanks 👍
      Just to make it clear: I'm not thinking about how to test the backend but how to handle real requests sent from the frontend during an integration or end-to-end test. E.g. testing a signup process will result in storing data in the database. You could create a database trigger which deletes data of a test user after insertion so that the signup process can be tested again with the same test data/ unique email. But there may be more elegant approaches?

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว +1

      I'd say to have a non production environment that can be blasted away whenever you'd like. Or something like stripe that gives you prod keys and also test keys.

    • @marvintrefzer8723
      @marvintrefzer8723 4 ปีที่แล้ว

      @@leighhalliday
      Don't you think a test environment - basically a clone of API and DB - is too much to deal with? How do you make sure it matches the actual production environment?
      After thinking about it again, I think in the scenario above you could simply test creating AND deleting a user. You could also test the scenario using the setup and teardown principle: For example, Cypress - an e2e testing tool - offers before() and after() hooks with which you could create and delete a user before and after the tests. Jest offers beforeAll() and afterAll()...
      What's your opinion?

  • @deeOOgh
    @deeOOgh 4 ปีที่แล้ว

    Fantastic, Thank you!

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Thanks Daniel, glad you enjoyed it!

  • @catehernandez5476
    @catehernandez5476 4 ปีที่แล้ว

    I'm 17 minutes in and I've watched at least 4 ads...that's if you don't count the times I tried to rewind and had to watch the same ad 3 more times. TH-cam, this is INSANE

    • @catehernandez5476
      @catehernandez5476 4 ปีที่แล้ว

      This video is awesome though thank you Leigh!!

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Hehe... sorry Cate! Glad you enjoyed it though :) Sorry about all the ads! I just have the default ad settings on so I can make a few bucks a month.

  • @davidwalters76
    @davidwalters76 4 ปีที่แล้ว

    And in Spanish as well! Now you're just showing off 😉 Helpful vid, thanks

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Hahaha... it's hard to make programming videos in Spanish for a non-native speaker. Glad you enjoyed it!

  • @MrOmarlive11
    @MrOmarlive11 4 ปีที่แล้ว

    Great Video thanks for sharing

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      You're welcome Omar, glad you enjoyed them!

  • @tambolaking5383
    @tambolaking5383 4 ปีที่แล้ว +1

    Too good

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Thank you very much Tambola!

    • @Norfeldt
      @Norfeldt 4 ปีที่แล้ว

      @@leighhalliday
      This video is absolutely fantastic! Thank you so much for sharing you knowledge - you are very skilled and updated on the latest react testing!
      I was wondering if you know how to spy on the server you make with msw?
      ...more Q details: 👉 stackoverflow.com/questions/63408769/jest-spy-on-mock-service-worker-msw

  • @nategage7180
    @nategage7180 4 ปีที่แล้ว

    Great video! Does this all set up similarly for a POST request?

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Thanks :) Yup! Same thing!

    • @nategage7180
      @nategage7180 4 ปีที่แล้ว

      sorry, just found the answer on the npm msw documentation haha.. subbed!

  • @tyranrecordslegacy
    @tyranrecordslegacy 3 ปีที่แล้ว

    this is great shit thanks mate

  • @gvsphaniteja
    @gvsphaniteja ปีที่แล้ว

    its for vue3 ? and also for jest or vitest?

  • @yoheihigashi457
    @yoheihigashi457 4 ปีที่แล้ว

    Hi, Leigh thank you so much for the video. It was really helpful!
    Would you be able to make React TDD Tutorial video with Redux(or context)?
    I'm really looking forward to watching more of your videos in the future.
    Greeting from Japan :)

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว +3

      Hey Yohei! Thanks so much :D Greetings from Canada! Probably more likely context than Redux (I don't use Redux very much). I'll do my best :)

    • @anthoniG
      @anthoniG 3 ปีที่แล้ว

      @@leighhalliday I'd buy that course :}
      The way you explain things is masterfully done.

  • @curiousprogrammer90
    @curiousprogrammer90 4 ปีที่แล้ว

    Nice, thanks.

  • @sunnygoel7365
    @sunnygoel7365 3 ปีที่แล้ว

    Would like to know the way to integrate MSW with functional UI Test and how to change responses for different tests .
    Thanks In Advance

    • @leighhalliday
      @leighhalliday  3 ปีที่แล้ว

      Hey Sunny! I'll keep this in mind for future videos :)

  • @avimehenwal
    @avimehenwal 2 ปีที่แล้ว

    Is it possible to use it in real - vuejs frontend application instead of testing code ? I am looking for a solution that could mock AUTH rewquests when I spin up my frontend application for local development. I dont want to run all our backend services to be able to develop it. Any help, suggestions, information in this direction would be highly appretiated. Super thanks for the video

  • @komalbashir2729
    @komalbashir2729 3 ปีที่แล้ว

    hi getting error of access key while calling api

  • @nikitaivochkin1742
    @nikitaivochkin1742 4 ปีที่แล้ว +1

    I can't understand why I've got this error "Error: Error: connect ECONNREFUSED 127.0.0.1:80" during tests

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว +1

      Hey Nikita! It sorta sounds like Mock Service Worker isn't blocking the request, it's getting through but then there is nothing running on localhost:80 to receive it. Double check that MSW is indeed configured correctly to stop outgoing requests to that address.

    • @nikitaivochkin1742
      @nikitaivochkin1742 4 ปีที่แล้ว

      @@leighhalliday thx for your feedback. Can it be connected that I use custom webpack config instead of react-create app in my project and also axios.create method?

    • @nikitaivochkin1742
      @nikitaivochkin1742 4 ปีที่แล้ว

      I solved my problem. The reason was with env variables. I guess env variables don't access in tests. Isn't it?

    • @YNA64
      @YNA64 3 ปีที่แล้ว +1

      @@nikitaivochkin1742 Hi Nikita , do you mind explaining a bit on what you did to solve this? I believe I'm facing the same issue. Thanks in advance.

    • @nikitaivochkin1742
      @nikitaivochkin1742 3 ปีที่แล้ว

      @@YNA64 My issue was connected to env variables. I set 'globals' key for jest config in package.json with my variables. It helped.

  • @ThukuWakogi
    @ThukuWakogi 4 ปีที่แล้ว

    Can this be used in testing a react native app?

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Not sure! Give it a try :D

    • @ThukuWakogi
      @ThukuWakogi 4 ปีที่แล้ว +1

      @@leighhalliday I did. it worked.

  • @viktorsoroka4510
    @viktorsoroka4510 4 ปีที่แล้ว

    Could you please compare why msw is better than pretenderjs for HTTP requests only?

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Hey Viktor! Sorry, I had never heard of pretenderjs :D I'm not as interested which one is better though... use whichever you enjoy more, or are more productive with!

    • @viktorsoroka4510
      @viktorsoroka4510 4 ปีที่แล้ว

      @@leighhalliday Makes sense, thank you for the great content. Glad that found your channel. Really amazed that you are reacting to every comment, at least in the comments in this video.

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      I try to reply to everyone :D Thanks for your support!

  • @alfonsoalejandroespinosade1728
    @alfonsoalejandroespinosade1728 4 ปีที่แล้ว

    hey Leigh, why do they take so long to run the test service? i see a lot of 8s, and there only 4 test

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว +1

      Hey Alfonso! I think a couple potential reasons... first I am recording the video which is making my computer suffer haha. Second, sometimes in react testing library, if it is looking for an element to appear on the screen and it isn't there, it waits a few seconds before giving up and deeming the test a failure.

  • @bigfoot3550
    @bigfoot3550 4 ปีที่แล้ว

    proper tutorial

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว +1

      Nice! Bigfoot is real and he's on TH-cam!! Thank you :)

  • @michaelporter2853
    @michaelporter2853 4 ปีที่แล้ว

    Would love to see the GraphQL version of this

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Me too hehe :D Perhaps at some point... I wonder how it would compare to using a mocked apollo provider?

    • @michaelporter2853
      @michaelporter2853 4 ปีที่แล้ว

      @@leighhalliday it looks to be a little easier but their example in the docs is not very complete.

  • @kenc1547
    @kenc1547 4 ปีที่แล้ว

    I encountered an error when i try to run the test. Error: SyntaxError: Cannot use import statement outside a module. I have added "type": "module" in the package.json file. Do you know what else is needed to perform import? Thanks

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Hmmm... honestly I haven't seen that before. Do you have a recent version of node? Are you doing it within create react app?

  • @flagoon
    @flagoon 4 ปีที่แล้ว

    I'll give it a try. Especially for mocking server when backend-boys are late.

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Yea for sure, seems like a good option for that... I haven't tried it out in the browser yet. Let us know!

  • @cgh2467
    @cgh2467 4 ปีที่แล้ว

    I don't get what the benefit this gives over just using something like fetch-mock which is far less setup.

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว +6

      One benefit is that it works for both fetch and axios, so you can take a single approach no matter how you're making HTTP requests.
      Another is that you can actually use the same mock definitions during development if your server implementation isn't ready yet.
      I like the abstraction it creates... rather than mocking out fetch, it sort of feels like you're just implementing the server, which as a mostly backend dev I like :D

  • @FordExplorer-rm6ew
    @FordExplorer-rm6ew 4 ปีที่แล้ว

    It's almost like this is an occulted technology.
    Nobody tells each other how it works.
    What's the closet I can get to best practice in production?

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      You mean regarding service workers? As far as learning, this seems really cool although I've never tried it: serviceworkies.com/

  • @nocoolming
    @nocoolming 4 ปีที่แล้ว

    good

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Thank you, I appreciate it :)

  • @adip9213
    @adip9213 3 ปีที่แล้ว

    Thank-you for this great video. Just wondering is it possible to move ```rest.get("api.exchangeratesapi.io/latest", (_req, res, ctx) => {
    return res(ctx.status(200), ctx.json({ rates: { CAD: 1.42 } }));
    })``` from the testServer to individual test cases ?

  • @revi_one
    @revi_one 3 ปีที่แล้ว

    where is the spanish video?

  • @saikrishna63
    @saikrishna63 4 ปีที่แล้ว

    Thanks for an awesome video, I have one query: I want to get the data for the first time from the internet web(my server) and further calls should be returned from the cache, is that possible ?

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Hey Sai! Great question, and the truth is that I don't know... you may want to reach out to the folks that create MSW and see if they have any insight

    • @aswaniduttaddaguduru
      @aswaniduttaddaguduru 4 ปีที่แล้ว

      @sai, I think you can achieve that using react-query

  • @larube
    @larube 4 ปีที่แล้ว

    Waiting for spanish Version !

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Hoy! Voy a grabarlo durante mi hora de almuerzo jaja

  • @nonefvnfvnjnjnjevjenjvonej3384
    @nonefvnfvnjnjnjevjenjvonej3384 3 ปีที่แล้ว

    the video is great but the problem with all of this is the amount of complexity and the time these tests take to run. 6 seconds for just a couple of tests. this is how CI gets bloated. With the JS ecosystem would focus on speed and performance like esbuild.

    • @leighhalliday
      @leighhalliday  3 ปีที่แล้ว

      It may just be overall bootup time? I don't think it is taking multiple seconds per test... at least I hope not haha!

  • @everydaywarriors
    @everydaywarriors 3 ปีที่แล้ว

    At 12:30 we got a sexchange

  • @gpcar7156
    @gpcar7156 4 ปีที่แล้ว

    Hi Leigh how are you!, talking about using mock axios, i try the mockAxios solution from www.leighhalliday.com/mocking-axios-in-jest-testing-async-functions and i see an small problem on my testing file, the first test it() mockaxios works perfect, but in the same file.test i had another test that test my main component so... the thing is that this component call a real axios request to another endpoint, so i dont know why (i mean, its another test) the axios.get used in still use the first MockAxios and of course the second test dont work very well because real axios in its expecting another result.data (not the fake one in __mock__/axio.js data:{}) i try afterEach(cleanup); but nothing happen. PS: Let me know if you are still practice spanish we can do language exchange maybe.

    • @leighhalliday
      @leighhalliday  4 ปีที่แล้ว

      Hey GP! Off the top of my head, honest answer is that I'm not sure :D Another solution is to give the Mock Service Worker a go like we cover in this video.

    • @gpcar7156
      @gpcar7156 4 ปีที่แล้ว

      @@leighhalliday i found my issue, the thing is that using a global mock like import __mock__/axios.js (with a default value) then ALL the test use the fake axios call, so no matter what you do, all the test in file start using the mock, so its a problem because maybe some component need the real axios call (default response in the mock not always fit all the calls for all the components needs of course) so... the solution when you test real axios and mock axios in the same test file is to use not the __mock__/axios.js but simply put this two lines: import axios from "axios"; and next line jest.mock('axios'); also must replace mockAxios.get.mockImplementationOnce for axios.get.mockResolvedValue thats it!!!. Muy buenos tus videos. Un abrazo.

  • @Human_Evolution-
    @Human_Evolution- 2 ปีที่แล้ว

    This seems confusing!@!@!!@!@!@!@!@!@!@ Why do QA devs get paid less when their work is 10 trillion times harder!!!!?