gpt4 book ai didi

javascript - 使用 Jest 测试 React/Redux 组件

转载 作者:行者123 更新时间:2023-12-02 21:01:38 25 4
gpt4 key购买 nike

我正在尝试使用 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接收到someBooleanfalse,它会调用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();
});

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

最佳答案

老实说,我建议不要使用 jest 的魔法来模拟导入。相反,您可以通过仅测试dumb组件并将所有函数作为 props 传递来简化测试。

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

关于javascript - 使用 Jest 测试 React/Redux 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61330479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com