使用jest,酶和路由器

时间:2017-11-04 10:27:58

标签: reactjs redirect react-router jestjs enzyme

您好我有一个问题我无法在github的项目中找到任何解决方案

我正在尝试使用react路由器作为上下文来测试条件(使用props)重定向,但由于呈现的实例为null,因此无法成功。这是错误消息:

ShallowWrapper::context() can only be called on wrapped nodes that have a non-null instance

这是我的组件:

import Router from "next/router";

export default (privateArea = props => {
  if (props.auth.isSignedIn === "SUCCESS") {
    Router.push("/");
  }
  return <p>You are in the private area</p>;
});

这是我的测试:

import privateArea from "./private";
import { shallow, configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
configure({ adapter: new Adapter() });

import { Router } from "next/router";
jest.mock("next/router");

describe("Redirect Test Suite", () => {
  let container, props;

  beforeEach(() => {
    store = mockStore(initialState);
    props = {
      auth: jest.fn(() => {})
    };
    const context = { router: new Router() };
    container = shallow(<privateArea {...props} />, { context });
  });

  it("renders without crashing", () => {
    expect(container).toBeDefined();
  });

  it("redirects when not Signed In", () => {
    container.setProps({ auth: { isSignedIn: "FAIL" } });
    expect(container.context("router")).toBeCalled();
  });

  it("renders when Signed In", () => {
    container.setProps({ auth: { isSignedIn: "SUCCESS" } });
    expect(container.context("router")).not.toHaveBeenCalled();
  });
});

感谢您的帮助/提示

最佳

0 个答案:

没有答案