簡體   English   中英

用 Jest 測試 React/Redux 組件

[英]Test React/Redux component with Jest

我正在嘗試使用 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");

我在其他地方有一個助手 function:

// 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();
});

但無論我做什么,它都不會通過。 正確的方法是什么?

老實說,我建議不要對 mocking 進口使用開玩笑的魔法。 取而代之的是,您可以通過僅測試啞組件並將所有函數作為道具傳遞來簡化測試。

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());
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM