我正在测试一些react组件,这是一个基本的测试套件,只是为了知道组件是否正在呈现及其子组件。
我使用redux-mock-store
创建存储库,并使用{mount}酶
在提供程序中装入容器,但即使是在模拟正确的存储库时,也总是会触发此错误:
TypeError:无法读取未定义的属性“pathname”
import React from 'react';
import { mount } from 'enzyme';
import configureStore from 'redux-mock-store';
import { Provider } from 'react-redux';
import App from '../containers/App.container';
describe('App', () => {
let wrapper;
const mockStore = configureStore([]);
const store = mockStore({
router: {
location: { pathname: '/home', query: {}, search: '' },
params: {}
}
});
console.log(store.getState());
beforeEach(() => {
wrapper = mount(
<Provider store={store}>
<App />
</Provider>
);
});
it('Should render app and container elements', () => {
expect(wrapper.find('.app').exists()).toBeTruthy();
expect(wrapper.find('.container').exists()).toBeTruthy();
});
it('Should render the navbar', () => {
expect(wrapper.find('nav').exists()).toBeTruthy();
});
});
和(甚至更简单的)组件/容器:
import React, { Component } from 'react';
import NavBar from '../components/Navbar';
class App extends Component {
render() {
const { location, logout} = this.props;
console.log(location);
return (
<section className='app'>
<NavBar location={location.pathname} onLogoutClick={logout}/>
<div className='container'>
{this.props.children}
</div>
</section>
);
}
}
export default App;
容器:
import { connect } from 'react-redux';
import { signOut } from '../actions/auth.actions'
import App from '../components/App';
const mapStateToProps = (state, ownProps) => {
return {
location: ownProps.location
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
logout: () => {
dispatch(signOut())
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
我搞不清楚测试的问题,mockStore的格式是正确的:
import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import { routerReducer } from 'react-router-redux';
import authReducer from './auth.reducer';
import analysisReportsReducer from './AnalysisReports.reducer';
import titleAnalysisReducer from './TitleAnalysis.reducer';
import postsReportsReducer from './PostsReports.reducer';
const rootReducer = combineReducers({
form: formReducer,
routing: routerReducer,
auth: authReducer,
analysis: titleAnalysisReducer,
analysis_reports: analysisReportsReducer,
posts: postsReportsReducer
});
export default rootReducer;
看起来您的location对象的作用域位于路由器下面。
假设测试是cli而不是在浏览器中,测试可能会抓取Window.Location属性,测试套件可能不会复制该属性。
也许试试:
<NavBar location={this.props.router.location.pathname} onLogoutClick={logout}/>
我已经禁用了react devtools和redux devtools。 几个小时以来,我一直在寻找处理这个问题的方法,大多数问题都在编写中,而我根本不改变代码。 我真不明白为什么会这样。我不做任何更改,我做的最后一件事只是做git,将origin master推到我的存储库中,当我编译时,突然出现了这样的错误: 还原:
使用“react-router-dom”:“^4.1.2”,“react-router-redux”:“^5.0.0-alpha.6”,在重定向完成后,我在console.log()中得到标题“uncatted typeerror:不能读取未定义的reacted Router redux的属性”type“。截图显示,包含有效载荷数据的可观察动作没有问题。有效负载包含表单数据(值)和历史对象。我设法
Helpe拜托。
如果函数在组件中,那么一切都很好。如果我把它单独取出并导出到一个组件中,那么我会得到一个错误TypeError:不能读取未定义的属性(读取'reduce')
main.jsx test.jsx