我正在编写一个单元测试来模拟按钮的单击。该按钮的onClick方法引用了使用props.history.push('/)加载另一页的方法。模拟工作正常,但开玩笑地说它无法读取属性推送,因为历史记录是不确定的,这会使测试失败。我如何在单元测试时添加props.history。我在做什么错了。
这是测试文件
import React from 'react';
import Landing from '../Components/Landing/Landing';
import configureStore from 'redux-mock-store';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import {StyleRoot}from 'radium';
import { Provider } from 'react-redux';
import { createMemoryHistory } from 'history';
Enzyme.configure({ adapter: new Adapter() });
const mockStore = configureStore();
let wrapper;
let store;
const initialState = {
auth:{
isLoggedIn:false,
role:''
},
};
const history = createMemoryHistory().push('/');
beforeEach(()=>{
store = mockStore(initialState);
wrapper = mount( <Provider store={store} >
<StyleRoot>
<Landing history={history}/>
</StyleRoot>
</Provider>
);
});
describe('Landing.js',()=>{
it ('Simulate click', ()=>{
const signInBtn = wrapper.find('.Btn');
signInBtn.simulate('click');
});
});
这是组件
const landing = props =>{
const loadSignInPage = ()=>{
props.history.push('/signin');
};
return(
<React.Fragment>
<Button buttonClass="SignIn" className="Btn" click={loadSignInPage}>SIGN IN</Button>
</React.Fragment>
);
};
const mapStateToProps = state =>{
return{
isLoggedIn: state.auth.isLoggedIn,
role: state.auth.role
};
};
export default connect(mapStateToProps)(landing);
错误
TypeError: Cannot read property 'push' of undefined
8 |
9 | const loadSignInPage = ()=>{
> 10 | props.history.push('/signin');
| ^
11 | };
在单元测试中如何添加props.history
答案 0 :(得分:2)
更改
const history = createMemoryHistory().push('/');
到
const history = createMemoryHistory();
history.push('/');
您当前的代码将history
的结果而不是push
的结果存储在createMemoryHistory()
中。
push
不返回任何内容。
参见https://github.com/ReactTraining/history/blob/master/modules/createMemoryHistory.js#L46-L89
答案 1 :(得分:1)
看起来像createMemoryHistory().push()
返回未定义。
试试这个吧。
const history = createMemoryHistory();
history.push('/');