Тёмный

React Testing Library Tutorial #13 - Mocking Requests 

Net Ninja
Подписаться 1,6 млн
Просмотров 69 тыс.
50% 1

Check out Laith's RU-vid channel for more tutorials:
/ @laithacademy
🐱‍💻 Access the course files on GitHub:
github.com/har...
🐱‍👤 Get access to extra premium courses on Net Ninja Pro:
netninja.dev
🐱‍💻 Full React Course:
• Full React Tutorial #1...
🐱‍💻 Social Links:
Facebook - / thenetninjauk
Twitter - / thenetninjauk
Instagram - / thenetninja

Опубликовано:

 

14 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 86   
@ferasmasoud428
@ferasmasoud428 2 года назад
Based on the last bug of testing, instead of changing node_modules, we can put: "jest": { "resetMocks": false }, in package.json
@jeremy-likes-cats
@jeremy-likes-cats 2 года назад
Thank you. Changing node_modules just didn't feel right.
@mahalingappabirajdar5285
@mahalingappabirajdar5285 Год назад
Great Thanks so much for the good suggestions.
@pvdevs
@pvdevs 9 месяцев назад
thanks!!
@yanaiedri
@yanaiedri 3 года назад
way change in node modules ??? you can change in the package.json - add a jest section like that: "jest": { "collectCoverageFrom": [ "src/**/*.{js,jsx,ts,tsx}" ], "resetMocks": false }
@shahmirjadoon3587
@shahmirjadoon3587 2 года назад
This really works. Thanks alot
@yanaiedri
@yanaiedri 2 года назад
@@shahmirjadoon3587 you Welcome :)
@tf1n
@tf1n 2 года назад
Mock service worker is a great solution for mocking different endpoints and routes. The docs are pretty clean and easy to follow along with.
@fotoflo
@fotoflo 3 года назад
Terrific series. Question: how can i mock different responses based on different URLs passed into Axios?
@mdridoy-ef2pw
@mdridoy-ef2pw 2 года назад
Same question. did you find any solution?
@kadirookirim3231
@kadirookirim3231 2 года назад
the best way is to use the "mock service worker" but if you want to use axios you can create an axios instance for every request : const getUsers=axios.create({ baseUrl: "...." method: 'get' }) you can use it every time you want to get users for example and mock it as well. const users =await getUsers(''/users"); (sorry my English)
@deepaknegi4385
@deepaknegi4385 2 года назад
@@kadirookirim3231 I agree, I use the same.
@suvendukumarsahoo4172
@suvendukumarsahoo4172 2 года назад
@@kadirookirim3231 can u explain how to post api call
@essaadi_elmehdi6784
@essaadi_elmehdi6784 2 года назад
We can mock the axios module by jest.mock('axios') example: import { render, screen } from "@testing-library/react"; import followersResp from "../../__mocks__/followers-response.json"; import { MemoryRouter } from "react-router-dom"; import FollowersList from "./FollowersList"; import axios from "axios"; jest.mock("axios"); describe("FollowersList", () => { test("should dispaly five followers", async () => { axios.get.mockResolvedValue(followersResp); render( ); const followers = await screen.findAllByTestId("follower-item"); expect(followers).toHaveLength(5); }); });
@suvendukumarsahoo4172
@suvendukumarsahoo4172 2 года назад
how to mock post api
@essaadi_elmehdi6784
@essaadi_elmehdi6784 2 года назад
@@suvendukumarsahoo4172 you use post instead of get in the same way
@suvendukumarsahoo4172
@suvendukumarsahoo4172 2 года назад
@@essaadi_elmehdi6784 i don't get it bro, can u have any example vdo regarding this
@azharponani
@azharponani 3 года назад
modifying node_modules will help us to pass tests only in our local machine right ? What if we have to run the tests in CI/CD pipelines ?
@codingintelugu8820
@codingintelugu8820 3 года назад
We can add resetMocks as false under jest in package.json file
@ashishmehradotdev
@ashishmehradotdev 3 года назад
If you're doing some changes in node_modules and want that to pass on CI/CD pipeline use patch-package .
@sonjamoamo5230
@sonjamoamo5230 3 года назад
I don't get this video. Is mocking the axios request (just by creating a folder __mocks___ and a file axios.js) supposed to take over the real axios request in FollowersList? How does this work? My tests still use the real axios request so am I missing something?
@ShashotoANur
@ShashotoANur 3 года назад
Same question. The component is still being rendered and useEffect hook is still executed which fetches data.
@sonjamoamo5230
@sonjamoamo5230 3 года назад
@@ShashotoANur Yes, I really don't get it. The ___mocks__ folder has no effect on my code.
@sonjamoamo5230
@sonjamoamo5230 3 года назад
@@ShashotoANur I used this code in the test file and it worked: jest.mock("axios", () => ({ __esModule: true, default: { get: () => ({ data: { results: [ { name: { ... }, picture: { ..., }, login: { ... }, }, ], }, }), }, }));
@virgiliogervacioestadillo1389
@virgiliogervacioestadillo1389 3 года назад
The reason why it uses the actual implementation of axios is because the jest.mock('axios', {...}) should be placed at the top of the describe block not inside the describe block.
@shadmanmartinpiyal4057
@shadmanmartinpiyal4057 3 года назад
the code in this video didn't work for me, i couldn't trigger a mock for axios. Anyway a quick solution is to put the following code inside the test file and everything will be working fine. Basically the code is for mocking "axios" jest.mock('axios', () => ({ __esModule: true, default: { get: () => ({ data:[ {userId:"not"}, {userId:"really"}, {userId:"one"} ] }) } }));
@ph3ed
@ph3ed 2 года назад
thanks, this is helpful
@MrFattylee
@MrFattylee 2 года назад
@@ph3ed Thanks, worked for me💌
@meghnathkar4342
@meghnathkar4342 2 года назад
Thanks, worked for me.
@qiqiliang7793
@qiqiliang7793 Год назад
You missed a part of the tutorial 8:41 he modified the node_modules folder. After changed the resetMocks to false, you should be good (keeps the src/__mocks__)
@qiqiliang7793
@qiqiliang7793 Год назад
If you delete the src/__mocks__ , the whole point of mocking get data from APIs is gone, so please keep the src/__mocks__ and follow 8:41
@PeterFullen
@PeterFullen 2 года назад
Do you have an example mocking using the msw library? Btw great videos!!!!!
@alinpetrusca9886
@alinpetrusca9886 3 года назад
Why not mocking the module directly in the test file ? Something like this: jest.mock('axios', () => ({ __esModule: true, get: () => ({ your: 'object' }) }));
@BookOfSaints
@BookOfSaints 3 года назад
This is my preferred approach (this or spyOn with mockImplementation on a per test basis). You don't have to modify an external file, and it gives you more flexibility for mocking, and also makes it very clear what the mock data you are returning looks like in the scope of that file or specific test
@alinpetrusca9886
@alinpetrusca9886 3 года назад
You probably need to mock the default export. Try something like this: jest.mock('axios', () => ({ __esModule: true, default: { get: () => ({ your: 'object' }) } })); or just jest.mock('axios');
@sonjamoamo5230
@sonjamoamo5230 3 года назад
I tried using this code in the same file as the test but it didn't work without wrapping the get in a default: {} property. Could you please explain why is that? And what's the point of __esModule: true? Thank you.
@BookOfSaints
@BookOfSaints 3 года назад
@@alinpetrusca9886 it is because axios is a default import (not named). Quoting an article I will link below, "In order to successfully mock a module with a default export, we need to return an object that contains a property for __esModule: true and then a property for the default export. This helps Jest correctly mock an ES6 module that uses a default export." Source codeburst.io/module-mocking-in-jest-ff174397e5ff
@alinpetrusca9886
@alinpetrusca9886 3 года назад
@@BookOfSaints My link described exactly what Sonja Moamo asked for. There is no need to delete comments just to show how smart you are :). Best regards.
@davem.6481
@davem.6481 2 года назад
Why is the __mocks__ folder put into the src folder? In the jest docs you can find that for mocking Node modules (like axios right?) "the mock should be placed in the __mocks__ directory adjacent to node_modules". Is it here different because of being a React project?
@donikastoqnova1734
@donikastoqnova1734 Год назад
Exellent compilation , showing the basics of testing with React.js.Everrything is very well explained. Thank you very much. In this particular video though , I got little confused. What exatly is mocking. What happens when use this method , are the tests go to the Server API , or not , and how we get the data. Thanks again.
@BrainwavesPotential
@BrainwavesPotential 2 года назад
Thank you so much for the videos, they were super helpful! Regarding this one: How about using spies? Wouldn't it be easier to mock requests? import axios from "axios"; const mockResponse = {...} describe("...", () => { const axiosSpy = jest.spyOn(axios, "get"); // Mock return value for test it("test case", () => { axiosSpy.mockResolvedValueOnce(mockResponse); }); });
@emmanuelbamidele5064
@emmanuelbamidele5064 8 месяцев назад
Thanks for this video, for the purpose of clarity can you confirm if giving this test the right name is what enables the api request to be able to be mocked as i see that in the testfile for the followerlist component this moked api call was not imported and nothing really refernced it... Thanks
@joaopaulorodriguespereira4768
@joaopaulorodriguespereira4768 3 года назад
And if I have another API in another file, how could I change the mocked data as in this case in receiving the same mocked data
@Nilkamalsha75
@Nilkamalsha75 3 года назад
If there are multiple apis in the application, how we can mock it ?
@coravityinfotech1660
@coravityinfotech1660 6 месяцев назад
Hey, there are external tools like MockServers, msw, requestly you can use them to create mocks.
@jdratlif
@jdratlif 2 года назад
mock service worker is a good alternative to mocking axios or fetch.
@kikevanegazz325
@kikevanegazz325 5 месяцев назад
How can you say that tests will run over and over in production? if your tests run in production, then the problem about resource consumption lies in the infrastructure, not the approach.
@arpithap7900
@arpithap7900 2 года назад
Yes same question here to why you wanna mock data something like that and modifying nodemodule is strictly not allowed. why can't use the approach jest.mock()
@gabrieludo3436
@gabrieludo3436 2 года назад
Thank you, Laith, great explanation
@susmitobhattacharyya1668
@susmitobhattacharyya1668 2 года назад
what if we have more than one endpoints to make a get call? you have shown it for a case where we are making the call to same endpoint.. please respond...thanks
@azfacts9968
@azfacts9968 2 года назад
This is great tutorial for react testing library
@NetNinja
@NetNinja 2 года назад
Glad it was helpful! :)
@dmitryrodetsky5573
@dmitryrodetsky5573 2 года назад
I switched out mocking of axios to the following approach: beforeEach(() => { //jest.mock("../../../__mocks__/axios") const mockGet = jest.spyOn(axios, 'get'); mockGet.mockImplementation(() => mockResponse) });
@arpithap7900
@arpithap7900 2 года назад
we can use Service worker too
@Human_Evolution-
@Human_Evolution- 2 года назад
Is this a unit test or an integration test?
@jayantsahoo1924
@jayantsahoo1924 2 года назад
How to test a dispatch inside a component and have .then() waiting for a response from the server? I want to write a test case for the save function inside my component which is triggering with fireEvent. onSave = () => { dispatch(createItem(payload)) .then(res => { if(res.code === 200 && res.status === 'OK'){ setSomeState(randomValue) } }) }; I want to let the execution go inside .then() block. how can we write the test case for this scenario with jest mock function?
@pro-cr2eo
@pro-cr2eo 3 года назад
great explanation. Thanks man!
@silvanadonato8446
@silvanadonato8446 Год назад
What if you want to use mocking in different pages?
@jenesg
@jenesg Год назад
You can use MSW for mocking.
@fredylagartija
@fredylagartija 2 года назад
what happen if a have to test several components that have axios get methods, and each one has different result structure
@codymccarty9327
@codymccarty9327 2 года назад
Great job asking for feedback on mocking API calls
@okechukwuobi3611
@okechukwuobi3611 2 года назад
How do you mock more that one API request to different test cases
@piyushpani4202
@piyushpani4202 2 года назад
can we use json server for mocking apis ?
@sagarreddy7461
@sagarreddy7461 3 года назад
thanks laith n shaun.
@09abhishekk
@09abhishekk 2 года назад
msw? Can we use it to mock http call?
@oubaidaawaw7271
@oubaidaawaw7271 7 месяцев назад
can we use postman to test api instead
@ChillCityNaveen
@ChillCityNaveen 3 года назад
very helpful
@vivekraj_kr
@vivekraj_kr 2 года назад
9:14 I didnt quite understand why it failed in the first place? Anyone?
@camdoes739
@camdoes739 3 года назад
i don't quite get why the Mocks resetting gives out an error
@suvendukumarsahoo4172
@suvendukumarsahoo4172 2 года назад
How to mock post api request
@sritimanadak3937
@sritimanadak3937 2 года назад
simpliest: jest.spyOn(axios,"get").mockReturnValue(mockResponse);
@ryder0078
@ryder0078 2 года назад
Lol changing node modules to fix your issue... bruh
@unnamedcodes
@unnamedcodes 5 месяцев назад
Can't stop laughing rn
Далее
ТИПИЧНОЕ ПОВЕДЕНИЕ МАМЫ
00:21
Просмотров 1,1 млн
Тренеруем память physics drop 103 - 104
00:51
Mocking Asynchronous Functions with Jest
21:50
Просмотров 71 тыс.
React Testing Library Tutorial #11 - Integration Tests
17:39
Mocking Axios in Jest + Testing Async Functions
17:43
React Testing Library Tutorial #10 - Fire Events
13:25
The Most Important Design Pattern in React
35:04
Просмотров 74 тыс.
Mock vs Spy in Testing with Jest: Which is Better?
25:12