gpt4 book ai didi

reactjs - 使用 Recompose 测试 HOC

转载 作者:行者123 更新时间:2023-11-28 20:36:31 26 4
gpt4 key购买 nike

我在测试一个 prop 在我的 HOC 上被触发时遇到了一些麻烦。

import { connect } from 'react-redux';
import { compose, lifecycle } from 'recompose';

import { fetchCurrentUser } from '../../actions/users';
import { getUser } from '../../reducers/users';
import User from '../../models/User';

export default Component => compose(
connect(state => ({
user: getUser(state),
}),
{ fetchCurrentUser }),
lifecycle({
componentDidMount() {
if (this.props.user instanceof User) return;
this.props.fetchCurrentUser();
},
}),
)(Component);

我想知道的是,当 user 不是 User 实例时,是否触发 fetchCurrentUser

到目前为止,我的测试中有:

it.only('fetches user if user is not a User instance', () => {
const setup = () => {
const props = {
user: 'string',
fetchCurrentUser: jest.fn(),
};
const enzymeWrapper = mounting(props);

return {
props,
enzymeWrapper,
};
};

// That returns 0 so false
expect(setup().props.fetchCurrentUser.mock.calls.length).toEqual(1);
});

看来我无法用这种方式替换 Prop 。如果我在生命周期方法中记录 this.props,我永远不会看到 user: 'string'

提前致谢

最佳答案

您需要对组件进行浅安装以测试其功能。

it.only('fetches user if user is not a User instance', () => {
const setup = () => {
const props = {
user: 'string',
fetchCurrentUser: jest.fn(),
};
// shallow render the component
const enzymeWrapper = shallow(<Component {...props} />)

return {
props,
enzymeWrapper,
};
};

expect(setup().props.fetchCurrentUser.mock.calls.length).toEqual(1);
});

关于reactjs - 使用 Recompose 测试 HOC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52476820/

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