React Router v4 Redirect unit test

后端 未结 3 1308
忘掉有多难
忘掉有多难 2021-02-04 00:50

How do I unit test the component in react router v4? I am unsuccessfully trying to unit test a simple component with a redirect using jest and enzyme.

My component:

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-04 01:19

    Here's my minimal example of testing that the actual URL changes instead of just that a Redirect component exists on the page:

    RedirectApp.js:

    import React from "react";
    import { Route, Switch, Redirect } from "react-router-dom";
    
    const RedirectApp = props => {
      return (
        
          
        
      );
    };
    
    export default RedirectApp;
    

    RedirectApp.test.js:

    import React from "react";
    import { MemoryRouter, Route } from "react-router-dom";
    import { mount } from "enzyme";
    import RedirectApp from "./RedirectApp";
    
    it("redirects /all-courses to /courses", () => {
      const wrapper = mount(
        
          
        
      );
    
      expect(wrapper.find(RedirectApp).props().location.pathname).toBe("/courses");
    });
    

    By wrapping RedirectApp in a Route, MemoryRouter injects the react-router props (match, location, and history) in RedirectApp.

    enzyme lets you grab these props(), and the location prop includes the pathname after redirect, so the redirected location can be matched.

    This method is a little hacky, but has the advantage of testing that a redirect is going to the correct place and not just that a Redirect exists.

    Alternatively, you can export default withRouter(RedirectApp) in RedirectApp.js to automatically get the react-router props injected.

提交回复
热议问题