Комментарии:
For api mock, instead of changing node_modules, we can simply have
beforeEach(()=>{
axios.get.mockResolvedValue(mockResponse)
})
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.
ОтветитьWhat if you want to use mocking in different pages?
ОтветитьYou can use MSW for mocking.
ОтветитьHow to mock post api request
ОтветитьbeforeEach(() => {
jest.restoreAllMocks();
})
I switched out mocking of axios to the following approach:
beforeEach(() => {
//jest.mock("../../../__mocks__/axios")
const mockGet = jest.spyOn(axios, 'get');
mockGet.mockImplementation(() => mockResponse)
});
This is great tutorial for react testing library
ОтветитьBased on the last bug of testing, instead of changing node_modules, we can put:
"jest": {
"resetMocks": false
},
in package.json
simpliest:
jest.spyOn(axios,"get").mockReturnValue(mockResponse);
Is this a unit test or an integration test?
Ответить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);
});
});
we can use Service worker too
Ответить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()
ОтветитьHow do you mock more that one API request to different test cases
ОтветитьLol changing node modules to fix your issue... bruh
ОтветитьMock service worker is a great solution for mocking different endpoints and routes. The docs are pretty clean and easy to follow along with.
Ответить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
Ответить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?
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);
});
});
what happen if a have to test several components that have axios get methods, and each one has different result structure
Ответитьcan we use json server for mocking apis ?
Ответитьmock service worker is a good alternative to mocking axios or fetch.
Ответить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?
ОтветитьThank you, Laith, great explanation
ОтветитьGreat job asking for feedback on mocking API calls
ОтветитьDo you have an example mocking using the msw library? Btw great videos!!!!!
Ответитьthanks laith n shaun.
Ответитьi don't quite get why the Mocks resetting gives out an error
Ответитьgreat explanation. Thanks man!
Ответить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"}
]
})
}
}));
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);
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?
ОтветитьTerrific series. Question: how can i mock different responses based on different URLs passed into Axios?
Ответить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.
If there are multiple apis in the application, how we can mock it ?
Ответить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
Ответитьvery helpful
ОтветитьAlso u can use dependency injection approach, but it’s pretty more complicated with the react, and pretty easy with the angular
ОтветитьWhy not mocking the module directly in the test file ? Something like this:
jest.mock('axios', () => ({
__esModule: true,
get: () => ({
your: 'object'
})
}));
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
}
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 ?