【问题标题】:Test React/Redux component with Jest用 Jest 测试 React/Redux 组件
【发布时间】:2020-04-20 19:27:52
【问题描述】:

我正在尝试使用 Jest 使用 Redux 测试 React 组件:

// components/MyComponent/index.js

class MyComponent extends React.Component {
  componentDidMount = () => {
    const { someBoolean } = this.props;
    if (someBoolean === false) {
      this.props.myFunction().then(() => myHelperFunction());
    }
  }

  render = () => {
    return <div>Something</div>;
  }
}

const mapStateToProps = (state) => {
  return { someBoolean: state.someBoolean };
}

export default connect(mapStateToProps, {
  myFunction,
})(MyComponent);

在组件中,如果props.myBoolean == false,将从这个Redux模块调用myFunction

// Redux/modules/MyModule/actions/someActions.js

export const someAction = (type) => (dispatch) => dispatch({ type });
export const myFunction = () => someAction("SOME_ACTION");

我在其他地方有一个辅助函数:

// tools/helpers.js

export const myHelperFunction = () => { // do stuff }

现在我想测试一下,如果MyComponent 接收到someBoolean 作为false,它会调用myFunction,然后调用myHelperFunction

// components/MyComponent/index.test.js

jest.mock("Redux/modules/MyModule/actions/someActions.js", () => ({
  myFunction: jest.fn(),
}));

jest.mock("tools/helpers.js", () => ({
  myHelperFunction: jest.fn(),
}));

it("should call myFunction when myBoolean is false", () => {
  const initialState = {
    myBoolean: false,
  };

  const holder = mountWithTheme(mockRedux(<MyComponent />, [], initialState));

  expect(myFunction).toHaveBeenCalled();
  expect(myHelperFunction).toHaveBeenCalled();
});

但无论我做什么,它都不会通过。正确的做法是什么?

【问题讨论】:

    标签: javascript reactjs unit-testing redux jestjs


    【解决方案1】:

    老实说,我建议不要使用 jest 的魔法来模拟导入。取而代之的是,您可以通过仅测试哑组件并将所有函数作为道具传递来简化测试。

    it("should call myFunction when myBoolean is false", () => {
      const props = {
        myBoolean: false,
        myFunction: jest.fn(),
        myHelperFunction: jest.fn()
      };
    
      const holder = mountWithTheme(<MyComponent {...props}/>);
    
      expect(myFunction).toHaveBeenCalled();
      expect(myHelperFunction).toHaveBeenCalled();
    });
    

    并对你的组件进行一些重构:

    componentDidMount = () => {
        const { someBoolean } = this.props;
        if (someBoolean === false) {
          this.props.myFunction().then(() => this.props.myHelperFunction());
        }
      }
    

    【讨论】:

    • 谢谢,但问题在于提供的课程。
    猜你喜欢
    • 2019-03-22
    • 2020-03-30
    • 1970-01-01
    • 2018-03-17
    • 2017-02-12
    • 2020-04-08
    • 2019-03-29
    • 2020-05-03
    • 2019-01-27
    相关资源
    最近更新 更多