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

前端 未结 3 2577
别那么骄傲
别那么骄傲 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:19

    Have you tried:

    describe("<Header/>", () => {
        it("call the header component", () => {
            const wrapper = shallow(<MemoryRouter initialEntries={['/abc']}><Header /></MemoryRouter>);
            expect(wrapper.find(Header).dive().find(ComponentA)).toHaveLength(1);
        });
    });
    

    When you use shallow only the first lvl is rendered, so you need to use dive to render another component.

    0 讨论(0)
  • 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("<ExampleComponent />", () => {
      it("should render ExampleComponent", () => {
        shallow(<ExampleComponent/>);
      });
    });
    

    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!

    0 讨论(0)
  • 2021-02-20 19:31

    I know this isn’t a direct answer to your question, but if what you want is to test the browser location or history, you can use mount and add an extra Route at the end where you can “capture” the history and location objects.

    test(`Foobar`, () => {
      let testHistory
      let testLocation
    
      const wrapper = mount(
        <MemoryRouter initialEntries={[`/`]}>
          <MyRoutes />
          <Route
            path={`*`}
            render={routeProps => {
              testHistory = routeProps.history
              testLocation = routeProps.location
              return null
            }}/>
        </MemoryRouter>
      )
    
      // Manipulate wrapper
    
      expect(testHistory)...
      expect(testLocation)...
    )}
    
    0 讨论(0)
提交回复
热议问题