React Testing Library Tutorial #13 - Mocking Requests

แชร์
ฝัง
  • เผยแพร่เมื่อ 16 ก.ย. 2024
  • Check out Laith's TH-cam 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

ความคิดเห็น • 86

  • @ferasmasoud428
    @ferasmasoud428 2 ปีที่แล้ว +156

    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 ปีที่แล้ว +20

      Thank you. Changing node_modules just didn't feel right.

    • @mahalingappabirajdar5285
      @mahalingappabirajdar5285 ปีที่แล้ว +2

      Great Thanks so much for the good suggestions.

    • @pvdevs
      @pvdevs 8 หลายเดือนก่อน +1

      thanks!!

  • @yanaiedri
    @yanaiedri 3 ปีที่แล้ว +221

    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 ปีที่แล้ว +1

      This really works. Thanks alot

    • @yanaiedri
      @yanaiedri 2 ปีที่แล้ว

      @@shahmirjadoon3587 you Welcome :)

  • @tf1n
    @tf1n 2 ปีที่แล้ว +10

    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 ปีที่แล้ว +32

    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 ปีที่แล้ว +1

      @@kadirookirim3231 can u explain how to post api call

  • @essaadi_elmehdi6784
    @essaadi_elmehdi6784 2 ปีที่แล้ว +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 ปีที่แล้ว +10

    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 .

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

    • @Charlie-ph3ed
      @Charlie-ph3ed 2 ปีที่แล้ว +1

      thanks, this is helpful

    • @MrFattylee
      @MrFattylee 2 ปีที่แล้ว +1

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

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

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

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

  • @PeterFullen
    @PeterFullen 2 ปีที่แล้ว +2

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

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

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

  • @davem.6481
    @davem.6481 2 ปีที่แล้ว +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?

  • @gabrieludo3436
    @gabrieludo3436 2 ปีที่แล้ว

    Thank you, Laith, great explanation

  • @azfacts9968
    @azfacts9968 2 ปีที่แล้ว

    This is great tutorial for react testing library

    • @NetNinja
      @NetNinja  2 ปีที่แล้ว

      Glad it was helpful! :)

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

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

  • @Nilkamalsha75
    @Nilkamalsha75 3 ปีที่แล้ว +3

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

    • @coravityinfotech1660
      @coravityinfotech1660 5 หลายเดือนก่อน

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

  • @emmanuelbamidele5064
    @emmanuelbamidele5064 7 หลายเดือนก่อน

    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

  • @pro-cr2eo
    @pro-cr2eo 3 ปีที่แล้ว

    great explanation. Thanks man!

  • @codymccarty9327
    @codymccarty9327 2 ปีที่แล้ว

    Great job asking for feedback on mocking API calls

  • @jdratlif
    @jdratlif 2 ปีที่แล้ว

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

  • @arpithap7900
    @arpithap7900 2 ปีที่แล้ว

    we can use Service worker too

  • @oubaidaawaw7271
    @oubaidaawaw7271 6 หลายเดือนก่อน

    can we use postman to test api instead

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

  • @sagarreddy7461
    @sagarreddy7461 3 ปีที่แล้ว

    thanks laith n shaun.

  • @kikevanegazz325
    @kikevanegazz325 4 หลายเดือนก่อน

    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.

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

  • @fredylagartija
    @fredylagartija 2 ปีที่แล้ว

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

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

  • @okechukwuobi3611
    @okechukwuobi3611 2 ปีที่แล้ว

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

  • @jenesg
    @jenesg ปีที่แล้ว

    You can use MSW for mocking.

  • @ChillCityNaveen
    @ChillCityNaveen 3 ปีที่แล้ว

    very helpful

  • @09abhishekk
    @09abhishekk 2 ปีที่แล้ว

    msw? Can we use it to mock http call?

  • @piyushpani4202
    @piyushpani4202 2 ปีที่แล้ว

    can we use json server for mocking apis ?

  • @Human_Evolution-
    @Human_Evolution- 2 ปีที่แล้ว

    Is this a unit test or an integration test?

  • @sritimanadak3937
    @sritimanadak3937 2 ปีที่แล้ว +2

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

  • @camdoes739
    @camdoes739 3 ปีที่แล้ว +1

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

  • @suvendukumarsahoo4172
    @suvendukumarsahoo4172 ปีที่แล้ว

    How to mock post api request

  • @ryder0078
    @ryder0078 2 ปีที่แล้ว +4

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

    • @unnamedcodes
      @unnamedcodes 4 หลายเดือนก่อน

      Can't stop laughing rn