ts+react 单元测试 测react-route

组件如下

import {Link, Route, Switch, Redirect, withRouter, RouteComponentProps} from "react-router-dom";

/** path of router */
export interface IRoutePath {
  a: string;
  b: string;
  c: string;
  d: string;
  e: string;
  f: string;
} 

//在组件的Prop接口中加 extends  RouteComponentProps 
export interface ITestDProps extends RouteComponentProps {
  // all router
  routePath: IRoutePath;
}
 
export class TestD extends React.Component {
 public render() {
    const {routePath} = {...this.props};
    return (
        <>
          e
          f
          
              组件e
              组件f
                //点击link d, 跳转到e,  这里的this.props.location.pathname就是当前路由
              {this.props.location.pathname === routePath.d? (
                
                  
                
              ) : null}
            
        
    );
  }


  /**
   * return link className
   * @param currentRouter `string` current router name
   */
  private linkClassName(currentRouter) {
    return this.props.location.pathname === currentRouter
      ? "links links-selected"
      : "links";
  }
}
 
export const TestDWithRoute= withRouter>(TestD);

测试如下  //注意,想要在项目中使用mocha请参考我其他文章

import {expect} from "chai";
import * as enzyme from "enzyme";
import * as Adapter from "enzyme-adapter-react-16";
import * as React from "react";
import * as TypeMoq from "typemoq";
import {IRoutePath } from "xxx"; //TestD组件的位置
import {TestD} from "xxx"; //TestD组件的位置
import {Link} from "react-router-dom";

enzyme.configure({adapter: new Adapter()});

const routePath: IRoutePath = {
      a: "/a",
      b: "/b",
      c: "/c",
      d: "/d",
      e: "/d/e",
      f: "/d/f",
};

describe("test TestD component", () => {
  let frame: any;
  beforeEach(async () => {
    const frames = () =>
      Promise.resolve(
        enzyme.shallow(
          
        )
      );
    frame = await frames();
  });
  afterEach(() => {
    frame.unmount();
  });

  it("navigation button which called 'e' connect to 'routePath.e'", () => {
    expect(frame.find(Link).at(0).prop("to")).equal(routePath.e);
  });

  it("navigation button which called 'f' connect to 'routePath.f'", () => {
    expect(frame.find(Link).at(1).prop("to")).equal(routePath.f);
  });

  it("when current router is 'routePath.e', the link of e is selected", () => {
    //修改prop pathname,就相当于修改路由
    frame.setProps({location: {hash: "", pathname: routePath.e, search: "", state: undefined}});
    expect(frame.find(".links-selected")).have.lengthOf(1);
  });
});

因为是项目的简化版,可能直接跑跑不通,请根据自己的项目自行修改

你可能感兴趣的:(react,react-router)