React Testing Library Tutorial #13 - Mocking Requests

Поділитися
Вставка
  • Опубліковано 6 січ 2025

КОМЕНТАРІ • 87

  • @ferasmasoud428
    @ferasmasoud428 2 роки тому +159

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

  • @yanaiedri
    @yanaiedri 3 роки тому +222

    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
    }

  • @tf1n
    @tf1n 2 роки тому +11

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

    • @MrBumbo90
      @MrBumbo90 Місяць тому

      msw is a godsent for mocking data.

  • @essaadi_elmehdi6784
    @essaadi_elmehdi6784 2 роки тому +5

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

  • @azharponani
    @azharponani 3 роки тому +12

    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 роки тому +10

      We can add resetMocks as false under jest in package.json file

    • @ashishmehradotdev
      @ashishmehradotdev 3 роки тому +1

      If you're doing some changes in node_modules and want that to pass on CI/CD pipeline use patch-package .

  • @sonjamoamo5230
    @sonjamoamo5230 3 роки тому +6

    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 роки тому +2

      Same question. The component is still being rendered and useEffect hook is still executed which fetches data.

    • @sonjamoamo5230
      @sonjamoamo5230 3 роки тому +1

      @@ShashotoANur Yes, I really don't get it. The ___mocks__ folder has no effect on my code.

    • @sonjamoamo5230
      @sonjamoamo5230 3 роки тому +1

      @@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.

  • @fotoflo
    @fotoflo 3 роки тому +33

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

    • @mdridoy-ef2pw
      @mdridoy-ef2pw 2 роки тому +2

      Same question.
      did you find any solution?

    • @kadirookirim3231
      @kadirookirim3231 2 роки тому +8

      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 роки тому +1

      @@kadirookirim3231 I agree, I use the same.

    • @suvendukumarsahoo4172
      @suvendukumarsahoo4172 2 роки тому +1

      @@kadirookirim3231 can u explain how to post api call

  • @shadmanmartinpiyal4057
    @shadmanmartinpiyal4057 3 роки тому +9

    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 роки тому +1

      thanks, this is helpful

    • @MrFattylee
      @MrFattylee 2 роки тому +1

      @@ph3ed Thanks, worked for me💌

    • @meghnathkar4342
      @meghnathkar4342 2 роки тому +1

      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

  • @joaopaulorodriguespereira4768
    @joaopaulorodriguespereira4768 3 роки тому +1

    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

  • @davem.6481
    @davem.6481 3 роки тому +1

    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?

  • @emmanuelbamidele5064
    @emmanuelbamidele5064 11 місяців тому

    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

  • @Nilkamalsha75
    @Nilkamalsha75 3 роки тому +3

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

    • @coravityinfotech1660
      @coravityinfotech1660 9 місяців тому

      Hey, there are external tools like MockServers, msw, requestly you can use them to create mocks.

  • @alinpetrusca9886
    @alinpetrusca9886 3 роки тому +10

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

    • @BookOfSaints
      @BookOfSaints 3 роки тому +2

      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 роки тому +7

      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 роки тому +1

      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 роки тому +4

      @@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.

  • @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

  • @PeterFullen
    @PeterFullen 3 роки тому +2

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

  • @dmitryrodetsky5573
    @dmitryrodetsky5573 2 роки тому +1

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

  • @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?

  • @okechukwuobi3611
    @okechukwuobi3611 2 роки тому

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

  • @silvanadonato8446
    @silvanadonato8446 Рік тому

    What if you want to use mocking in different pages?

  • @vivekraj_kr
    @vivekraj_kr 2 роки тому

    9:14 I didnt quite understand why it failed in the first place? Anyone?

  • @gabrieludo3436
    @gabrieludo3436 3 роки тому

    Thank you, Laith, great explanation

  • @jdratlif
    @jdratlif 3 роки тому

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

  • @kikevanegazz325
    @kikevanegazz325 8 місяців тому

    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.

  • @oubaidaawaw7271
    @oubaidaawaw7271 10 місяців тому

    can we use postman to test api instead

  • @09abhishekk
    @09abhishekk 2 роки тому

    msw? Can we use it to mock http call?

  • @BrainwavesPotential
    @BrainwavesPotential 2 роки тому +6

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

  • @piyushpani4202
    @piyushpani4202 3 роки тому

    can we use json server for mocking apis ?

  • @azfacts9968
    @azfacts9968 2 роки тому

    This is great tutorial for react testing library

    • @NetNinja
      @NetNinja  2 роки тому

      Glad it was helpful! :)

  • @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.

  • @Human_Evolution-
    @Human_Evolution- 2 роки тому

    Is this a unit test or an integration test?

  • @pro-cr2eo
    @pro-cr2eo 3 роки тому

    great explanation. Thanks man!

  • @camdoes739
    @camdoes739 3 роки тому +1

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

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

  • @arpithap7900
    @arpithap7900 2 роки тому

    we can use Service worker too

  • @jenesg
    @jenesg 2 роки тому

    You can use MSW for mocking.

  • @codymccarty9327
    @codymccarty9327 3 роки тому

    Great job asking for feedback on mocking API calls

  • @suvendukumarsahoo4172
    @suvendukumarsahoo4172 2 роки тому

    How to mock post api request

  • @sagarreddy7461
    @sagarreddy7461 3 роки тому

    thanks laith n shaun.

  • @ChillCityNaveen
    @ChillCityNaveen 3 роки тому

    very helpful

  • @sritimanadak3937
    @sritimanadak3937 2 роки тому +2

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

  • @ryder0078
    @ryder0078 2 роки тому +4

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