如何使用Jest&Enzyme测试此React HOC组件?

时间:2019-07-02 09:36:03

标签: reactjs jestjs enzyme

React和单元测试的新手,我尝试测试该组件,但是结果却不是我期望的。无论我将道具设置为真还是假。测试总是通过的。谁能帮我吗?

我尝试了模拟商店。

我要进行单元测试的组件:

/* eslint react/no-unused-prop-types:0 */
import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { login } from "../utils/authentication";

// A parent container which checks if the user is logged in before rendering its children
// If the user is not logged in, a login action is initiated
class RequiresAuthentication extends Component {
  componentDidMount() {
    this.doLoginIfRequired();
  }

  componentDidUpdate() {
    this.doLoginIfRequired();
  }

  doLoginIfRequired() {
    const { userInitialised, hasAccess } = this.props;
    if (userInitialised && !hasAccess) {
      login.doLogin();
      return false;
    }
    return true;
  }

  render() {
    const { hasAccess, children } = this.props;
    if (!hasAccess) return null;
    return <Fragment>{children}</Fragment>;
  }
}

RequiresAuthentication.propTypes = {
  hasAccess: PropTypes.bool,
  userInitialised: PropTypes.bool,
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node
  ])
};

const mapStateToProps = state => ({
  hasAccess: state.auth.hasAccess,
  userInitialised: state.auth.userInitialised
});

export default connect(mapStateToProps)(RequiresAuthentication);

我编写的测试:

import React from "react";
import { shallow } from "enzyme";
import configureStore from "redux-mock-store";
import Auth from "./RequiresAuthentication";


let store;

describe("<Auth />", () => {
  beforeEach(() => {
    const mockStore = configureStore();
    store = mockStore({
      auth: {
        hasAccess: false,
        userInitialised: false
      }
    });
  });
  it("Should render the component only when auth props are true", () => {
    const wrapper = shallow(
      <Auth store={store}>
        <h1 className="hello">Hello</h1>
      </Auth>
    );
    expect(wrapper).not.toBe(null);
  });
});

道具是假的。测试应该失败。但事实并非如此。如何正确测试此组件?任何帮助是极大的赞赏。谢谢! ??

0 个答案:

没有答案