How do you mock useLocation() pathname using shallow test enzyme Reactjs?

前端 未结 3 2456
别那么骄傲
别那么骄傲 2021-02-20 18:56

I have header component like below:

import { useLocation } from \"react-router-dom\";

const Header = () => {
   let route = useLocation().pathname; 
   retur         


        
3条回答
  •  不知归路
    2021-02-20 19:21

    I found that I can mock the React Router hooks like useLocation using the following pattern:

    import React from "react"
    import ExampleComponent from "./ExampleComponent"
    import { shallow } from "enzyme"
    
    jest.mock("react-router-dom", () => ({
      ...jest.requireActual("react-router-dom"),
      useLocation: () => ({
        pathname: "localhost:3000/example/path"
      })
    }));
    
    describe("", () => {
      it("should render ExampleComponent", () => {
        shallow();
      });
    });
    

    If you have a call to useLocation in your ExampleComponent the above pattern should allow you to shallow render the component in an Enzyme / Jest test without error. Hope that helps!

提交回复
热议问题