我正在尝试使用Jest和Enzyme测试react-redux组件。
我通过了基本的渲染测试 但是无法在componentDidMount中测试自定义方法的调用时间。
MyButton.jsx
class MyButton extends React.Component {
constructor(props) {
this.handleDataLoad = this.handleDataLoad.bind(this);
}
componentDidMount() {
this.handleDataLoad();
}
handleDataLoad() {
console.log('handleDataLoad call');
}
render() {
{/* ... */}
}
}
const mapStateToProps = state => (/* ... */);
export default connect(mapStateToProps)(MyButton);
MyButton.spec.jsx
import React from 'react';
import { shallow } from 'enzyme';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import MyButton from './MyButton';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe('MyButton', () => {
const initialState = {};
const props = {
/* ...required props... */
};
const store = mockStore(initialState);
const component = shallow(<MyButton store={store} {...props} />);
const didMount = jest.spyOn(OrderBook.prototype, 'componentDidMount');
const mockHandleDataLoad = jest.spyOn(component.dive().instance(), 'handleDataLoad');
describe('with enzyme', () => {
it('called componentDidMount', () => {
expect(didMount).toHaveBeenCalledTimes(1);
}); // this is passed.
it('called handleScrollEventAttach', () => {
expect(mockHandleScrollEventAttach).toHaveBeenCalledTimes(1);
}); // this is fail.
});
});
第二条测试消息是“预期的模拟函数已被调用一次,但被调用了零次。”
我认为'handleDataLoad'应该被调用一次,因为componentDidMount被调用了。但这不是。
如何在React Life Cycle方法中知道'handleDataLoad'的调用时间? 不可能吗?
package.json
"react": "15.6.2",
"react-dom": "15.6.2",
"react-redux": "5.0.7",
"redux": "3.7.2",
"babel-jest": "23.2.0",
"enzyme": "^3.7.0",
"enzyme-adapter-react-15": "^1.1.1",
"enzyme-to-json": "^3.3.4",
"react-test-renderer": "15.6.1",
"redux-mock-store": "^1.5.3",
答案 0 :(得分:1)
const mockHandleDataLoad = jest.spyOn(component.dive()。instance(),'mockHandleDataLoad');
应该是
const mockHandleDataLoad = jest.spyOn(component.dive().instance(), 'handleDataLoad');
在监视组件实例时,应提供实际的函数名称。
我还注意到您在嘲笑商店,您真的要测试连接的组件吗?您只能通过导出来测试内部组件,请选中https://github.com/reduxjs/redux/blob/master/docs/recipes/WritingTests.md
答案 1 :(得分:0)
我建议将MyButton.jsx分为:
MyButton/Component.jsx (holds your component implementation)
MyButton/Container.js (will connect your component to Redux store)
通过这种方式,您将能够毫无问题地测试您的组件。而且将来您可以替换Redux。