React Testing Library Tutorial #13 - Mocking Requests

  Рет қаралды 66,639

Net Ninja

Net Ninja

Күн бұрын

Check out Laith's KZfaq channel for more tutorials:
/ @laithacademy
🐱‍💻 Access the course files on GitHub:
github.com/harblaith7/React-T...
🐱‍👤 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

Пікірлер: 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 Жыл бұрын
Thank you. Changing node_modules just didn't feel right.
@mahalingappabirajdar5285
@mahalingappabirajdar5285 Жыл бұрын
Great Thanks so much for the good suggestions.
@pvdevs
@pvdevs 6 ай бұрын
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.
@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?
@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
@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 Жыл бұрын
@@kadirookirim3231 can u explain how to post api call
@gabrieludo3436
@gabrieludo3436 2 жыл бұрын
Thank you, Laith, great explanation
@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 Жыл бұрын
how to mock post api
@essaadi_elmehdi6784
@essaadi_elmehdi6784 Жыл бұрын
@@suvendukumarsahoo4172 you use post instead of get in the same way
@suvendukumarsahoo4172
@suvendukumarsahoo4172 Жыл бұрын
@@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 .
@pro-cr2eo
@pro-cr2eo 2 жыл бұрын
great explanation. Thanks man!
@emmanuelbamidele5064
@emmanuelbamidele5064 6 ай бұрын
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
@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
@fredylagartija
@fredylagartija 2 жыл бұрын
what happen if a have to test several components that have axios get methods, and each one has different result structure
@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.
@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"} ] }) } }));
@Charlie-ph3ed
@Charlie-ph3ed 2 жыл бұрын
thanks, this is helpful
@MrFattylee
@MrFattylee 2 жыл бұрын
@@Charlie-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
@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?
@PeterFullen
@PeterFullen 2 жыл бұрын
Do you have an example mocking using the msw library? Btw great videos!!!!!
@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 ?
@Nilkamalsha75
@Nilkamalsha75 3 жыл бұрын
If there are multiple apis in the application, how we can mock it ?
@coravityinfotech1660
@coravityinfotech1660 3 ай бұрын
Hey, there are external tools like MockServers, msw, requestly you can use them to create mocks.
@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); }); });
@dmitryrodetsky5573
@dmitryrodetsky5573 Жыл бұрын
I switched out mocking of axios to the following approach: beforeEach(() => { //jest.mock("../../../__mocks__/axios") const mockGet = jest.spyOn(axios, 'get'); mockGet.mockImplementation(() => mockResponse) });
@silvanadonato8446
@silvanadonato8446 Жыл бұрын
What if you want to use mocking in different pages?
@09abhishekk
@09abhishekk Жыл бұрын
msw? Can we use it to mock http call?
@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.
@jdratlif
@jdratlif 2 жыл бұрын
mock service worker is a good alternative to mocking axios or fetch.
@oubaidaawaw7271
@oubaidaawaw7271 5 ай бұрын
can we use postman to test api instead
@Human_Evolution-
@Human_Evolution- 2 жыл бұрын
Is this a unit test or an integration test?
@ChillCityNaveen
@ChillCityNaveen 3 жыл бұрын
very helpful
@azfacts9968
@azfacts9968 2 жыл бұрын
This is great tutorial for react testing library
@NetNinja
@NetNinja 2 жыл бұрын
Glad it was helpful! :)
@codymccarty9327
@codymccarty9327 2 жыл бұрын
Great job asking for feedback on mocking API calls
@vivekraj_kr
@vivekraj_kr 2 жыл бұрын
9:14 I didnt quite understand why it failed in the first place? Anyone?
@sagarreddy7461
@sagarreddy7461 2 жыл бұрын
thanks laith n shaun.
@suvendukumarsahoo4172
@suvendukumarsahoo4172 Жыл бұрын
How to mock post api request
@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()
@camdoes739
@camdoes739 2 жыл бұрын
i don't quite get why the Mocks resetting gives out an error
@arpithap7900
@arpithap7900 2 жыл бұрын
we can use Service worker too
@jenesg
@jenesg Жыл бұрын
You can use MSW for mocking.
@sritimanadak3937
@sritimanadak3937 2 жыл бұрын
simpliest: jest.spyOn(axios,"get").mockReturnValue(mockResponse);
@ryder0078
@ryder0078 2 жыл бұрын
Lol changing node modules to fix your issue... bruh
@unnamedcodes
@unnamedcodes 2 ай бұрын
Can't stop laughing rn
@kikevanegazz325
@kikevanegazz325 2 ай бұрын
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.
React Testing Library Tutorial #14 - Before &After Each
5:25
Net Ninja
Рет қаралды 31 М.
Женская драка в Кызылорде
00:53
AIRAN
Рет қаралды 506 М.
World’s Largest Jello Pool
01:00
Mark Rober
Рет қаралды 99 МЛН
Best KFC Homemade For My Son #cooking #shorts
00:58
BANKII
Рет қаралды 68 МЛН
Testing In React Tutorial - Jest and React Testing Library
21:28
Why Vitest Is Better Than Jest
13:13
Web Dev Simplified
Рет қаралды 131 М.
Mocking Asynchronous Functions with Jest
21:50
Swashbuckling with Code
Рет қаралды 68 М.
React Testing Tutorial with React Testing Library and Jest
41:43
Stop Writing So Many Tests
10:02
Web Dev Simplified
Рет қаралды 85 М.
Mock Service Worker with React
39:20
Anson the Developer
Рет қаралды 10 М.
JavaScript Testing - Mocking Async Code
18:05
Academind
Рет қаралды 145 М.
Женская драка в Кызылорде
00:53
AIRAN
Рет қаралды 506 М.