Javascript 使用特定道具进行连接部件测试(React/Redux)
我有一个带有Redux@connect decorator的react组件,例如:Javascript 使用特定道具进行连接部件测试(React/Redux),javascript,reactjs,unit-testing,react-redux,jestjs,Javascript,Reactjs,Unit Testing,React Redux,Jestjs,我有一个带有Redux@connect decorator的react组件,例如: import React, { Component } from 'react' import { connect } from 'react-redux' @connect(mapStateToProps, { onPress: () => {...code}) // Component receives this func, not passed from the test } expor
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>
}
}
import React,{Component}来自“React”
从“react redux”导入{connect}
@连接(MapStateTops,
{
onPress:()=>{…code})//组件接收此func,但未从测试中传递
}
导出类组件扩展组件{
渲染(){
返回。。。。
}
}
我遇到了一个问题,即在测试文件中传递给组件的模拟函数没有传递给组件:
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);
});
});
const store=createStore(
组合减速器({name:reducer})
);
const ComponentConnected=连接({
onPress:{jest.fn()}//组件未接收此模拟
})(() =>());
描述('组件测试',()=>{
它('应该呈现组件',()=>{
常量包装器=装入(
);
expect(wrapper.find(Component)).toHaveLength(1);
});
});
此外,我尝试将模拟函数作为测试组件道具传递,但也没有帮助。不重新编写component@connect decorator就可以解决这个问题吗?我认为,不必模仿redux connect的connect函数。你应该嘲笑行为本身。用操作文件替换
。/actions
import { onPress } from "../actions";
jest.mock("../actions");
onPress.mockReturnValue({ someval: 1 });
我想,与其模仿redux connect的connect函数,不如说是。你应该嘲笑行为本身。用操作文件替换
。/actions
import { onPress } from "../actions";
jest.mock("../actions");
onPress.mockReturnValue({ someval: 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'});
});
});
description('组件测试',()=>{
它('应该呈现组件',()=>{
常数包装=浅(
);
const connectedComponentWrapper=wrapper.dive().dive();
connectedComponentWrapper.setProps({anyProp:'anyProp'});
});
});
我发现了如何将道具传递给连接的组件。我使用了浅层、潜水和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'});
});
});
description('组件测试',()=>{
它('应该呈现组件',()=>{
常数包装=浅(
);
const connectedComponentWrapper=wrapper.dive().dive();
connectedComponentWrapper.setProps({anyProp:'anyProp'});
});
});