React Testing Library Tutorial #13 - Mocking Requests

React Testing Library Tutorial #13 - Mocking Requests

Net Ninja

3 года назад

66,653 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

Neha Mundra
Neha Mundra - 12.04.2023 19:20

For api mock, instead of changing node_modules, we can simply have
beforeEach(()=>{
axios.get.mockResolvedValue(mockResponse)
})

Ответить
Donika Stoqnova
Donika Stoqnova - 02.03.2023 16:24

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.

Ответить
Silvana Donato
Silvana Donato - 28.01.2023 18:12

What if you want to use mocking in different pages?

Ответить
Géza Jenes
Géza Jenes - 19.11.2022 17:53

You can use MSW for mocking.

Ответить
Suvendu Kumar Sahoo
Suvendu Kumar Sahoo - 22.10.2022 13:18

How to mock post api request

Ответить
Wei Zhang
Wei Zhang - 02.10.2022 15:37

beforeEach(() => {
jest.restoreAllMocks();
})

Ответить
Dmitry Rodetsky
Dmitry Rodetsky - 15.09.2022 01:44

I switched out mocking of axios to the following approach:
beforeEach(() => {
//jest.mock("../../../__mocks__/axios")
const mockGet = jest.spyOn(axios, 'get');
mockGet.mockImplementation(() => mockResponse)
});

Ответить
AZ Facts
AZ Facts - 24.07.2022 14:34

This is great tutorial for react testing library

Ответить
Feras Masoud
Feras Masoud - 17.07.2022 18:56

Based on the last bug of testing, instead of changing node_modules, we can put:
"jest": {
"resetMocks": false
},
in package.json

Ответить
Sri Ti Man Ad Ak
Sri Ti Man Ad Ak - 15.07.2022 18:42

simpliest:
jest.spyOn(axios,"get").mockReturnValue(mockResponse);

Ответить
Human Evolution
Human Evolution - 22.06.2022 05:06

Is this a unit test or an integration test?

Ответить
ESSAADI_ ELMEHDI
ESSAADI_ ELMEHDI - 17.06.2022 15:57

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(
<MemoryRouter>
<FollowersList />
</MemoryRouter>
);

const followers = await screen.findAllByTestId("follower-item");

expect(followers).toHaveLength(5);
});
});

Ответить
Arpitha P
Arpitha P - 02.05.2022 14:05

we can use Service worker too

Ответить
Arpitha P
Arpitha P - 02.05.2022 14:04

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()

Ответить
Okechukwu Obi
Okechukwu Obi - 18.03.2022 19:20

How do you mock more that one API request to different test cases

Ответить
Ray
Ray - 17.03.2022 04:51

Lol changing node modules to fix your issue... bruh

Ответить
Cameron Colaco
Cameron Colaco - 04.03.2022 09:22

Mock service worker is a great solution for mocking different endpoints and routes. The docs are pretty clean and easy to follow along with.

Ответить
Susmito Bhattacharyya
Susmito Bhattacharyya - 06.02.2022 23:22

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

Ответить
jayant sahoo
jayant sahoo - 03.02.2022 11:43

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?

Ответить
Brainwaves Potential
Brainwaves Potential - 31.01.2022 15:33

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);
});
});

Ответить
Fredy
Fredy - 30.01.2022 06:59

what happen if a have to test several components that have axios get methods, and each one has different result structure

Ответить
piyush pani
piyush pani - 13.01.2022 08:43

can we use json server for mocking apis ?

Ответить
John Ratliff
John Ratliff - 02.01.2022 02:42

mock service worker is a good alternative to mocking axios or fetch.

Ответить
Dave M.
Dave M. - 28.12.2021 13:02

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?

Ответить
Gabriel Udo
Gabriel Udo - 24.12.2021 20:54

Thank you, Laith, great explanation

Ответить
Cody McCarty
Cody McCarty - 10.12.2021 11:10

Great job asking for feedback on mocking API calls

Ответить
Nerdo Monkey
Nerdo Monkey - 12.11.2021 23:30

Do you have an example mocking using the msw library? Btw great videos!!!!!

Ответить
sagar reddy
sagar reddy - 01.10.2021 17:23

thanks laith n shaun.

Ответить
cam ____
cam ____ - 24.09.2021 00:50

i don't quite get why the Mocks resetting gives out an error

Ответить
pro
pro - 28.08.2021 13:02

great explanation. Thanks man!

Ответить
Shadman Martin Piyal
Shadman Martin Piyal - 07.08.2021 16:07

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"}
]
})
}
}));

Ответить
박재영
박재영 - 06.08.2021 18:15

According to the official document(Manual Mocks), the mock should be placed in the _mocks_ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root). Then the mock test will not fail. Another way is inserting this directly.
ex)
jest.mock("axios");
axios.get.mockResolvedValue(mockResponse);

Ответить
S B
S B - 31.07.2021 12:46

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?

Ответить
Alex Miller
Alex Miller - 23.07.2021 08:33

Terrific series. Question: how can i mock different responses based on different URLs passed into Axios?

Ответить
Drew Stifler
Drew Stifler - 21.07.2021 05:54

Instead of creating a mock folder and configuring stuffs, I prefer inserting this directly to the test func

jest.mock('axios', () => ({
__esModule: true,
get: () => ({
data: {
results: [
{
name: {
first: 'Mark'
...
},
...
},
]
}
})
}));

credits to Alin Petrusca.

Ответить
Nilkamal Shah
Nilkamal Shah - 19.07.2021 15:28

If there are multiple apis in the application, how we can mock it ?

Ответить
Joao Paulo Rodrigues Pereira
Joao Paulo Rodrigues Pereira - 19.07.2021 02:05

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

Ответить
Chill City Naveen
Chill City Naveen - 16.07.2021 16:54

very helpful

Ответить
Евгений Попов
Евгений Попов - 16.07.2021 04:06

Also u can use dependency injection approach, but it’s pretty more complicated with the react, and pretty easy with the angular

Ответить
Alin Petrusca
Alin Petrusca - 15.07.2021 16:16

Why not mocking the module directly in the test file ? Something like this:
jest.mock('axios', () => ({
__esModule: true,
get: () => ({
your: 'object'
})
}));

Ответить
yanai edri
yanai edri - 15.07.2021 14:00

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
}

Ответить
Mohammed Azhar
Mohammed Azhar - 15.07.2021 11:27

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 ?

Ответить