我有一个带有Redux @connect装饰器的react组件,例如:
import React, { Component } from 'react'
import { connect } from 'react-redux'
@connect(mapStateToProps,
{
onPress: () => {...code}) // Component receives this func, not passed from the test
}
export class Component extends Component {
render () {
return <button onclick={this.props.onPress>....</button>
}
}
我遇到了一个问题,即在测试文件中传递给组件的模拟函数没有传递给组件:
const store = createStore(
combineReducers({name: reducer})
);
const ComponentConnected = connect(..., {
onPress: {jest.fn()} // Component doesn't receive this mock
})(() =>(<Component />));
describe('Component testing', () => {
it('should render component', () => {
const wrapper = mount(
<Provider store={store}>
<ComponentConnected />
</Provider>
);
expect(wrapper.find(Component)).toHaveLength(1);
});
});
此外,我尝试将模拟功能作为经过测试的组件prop传递,它也无济于事。无需重写组件@connect装饰器就可以解决此问题吗?
答案 0 :(得分:1)
我认为,不是嘲笑redux-connect的connect函数。您应该模拟动作本身。将../actions
替换为您的操作文件。
import { onPress } from "../actions";
jest.mock("../actions");
onPress.mockReturnValue({ someval: 1 });
答案 1 :(得分:1)
我发现了如何将道具传递给连接的组件。我使用了浅水,潜水和setProps酶方法:
describe('Component testing', () => {
it('should render component', () => {
const wrapper = shallow(
<Provider store={store}>
<ComponentConnected />
</Provider>
);
const connectedComponentWrapper = wrapper.dive().dive();
connectedComponentWrapper.setProps({anyProp: 'anyProp'});
});
});