【发布时间】:2018-10-25 05:25:24
【问题描述】:
我最近想测试在 React 组件的 componentDidMount 方法中调用了一些自定义方法。
componentDidMount() {
this.props.actions.getDocuments();
}
我使用 Jest 作为我的测试框架,其中包括用于模拟/间谍的 jest.fn()
function setup(data) {
const props = {
session: {},
actions: {
getDocuments: jest.fn()
}
};
const wrapper = mount(<ComponentList {...props} />,
{
context: { muiTheme: getMuiTheme() },
childContextTypes: { muiTheme: React.PropTypes.object.isRequired }
}
);
return {
props,
wrapper
};
}
describe('compenent:', () => {
let component;
describe('Given that the container is loaded', () => {
beforeAll(() => {
component = setup();
});
it('should call the getDocuments to get the data', () => {
expect(component.props.actions.getDocuments).toHaveBeenCalled();
});
});
});
此代码失败并抛出以下错误:
TypeError: received.getMockName is not a function
at Object.<anonymous> (src/containers/ComponentList/ComponentList.spec.js:61:158)
at new Promise (<anonymous>)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
如果我使用 sinon 而不是 jest,我仍然会收到错误:
expect(jest.fn())[.not].toHaveBeenCalled()
jest.fn() value must be a mock function or spy.
Received:
function: [Function proxy]
at Object.<anonymous> (src/containers/ComponentList/ComponentList.spec.js:61:158)
at new Promise (<anonymous>)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
是否可以使用 Jest 或 Sinon 测试此功能?如果有,怎么做?
这是我的代码实现:
export class ComponentList extends React.Component {
constructor(props) {
super(props)
}
componentDidMount() {
this.props.actions.getDocuments();
}
render() {
return (
<div className="allowScroll">
....
</div>
)
}
}
ComponentList.propTypes = {
document: PropTypes.object,
actions: PropTypes.object.isRequired
};
const mapStateToProps = (state) => {
return {
document: state.document
}
};
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(componentActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(ComponentList)
【问题讨论】:
标签: reactjs unit-testing testing jestjs enzyme