当前位置: 首页 > 知识库问答 >
问题:

TypeError:无法读取react/redux测试中未定义的属性“pathname”

曹涵润
2023-03-14

我正在测试一些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;

共有1个答案

龙嘉玉
2023-03-14

看起来您的location对象的作用域位于路由器下面。

假设测试是cli而不是在浏览器中,测试可能会抓取Window.Location属性,测试套件可能不会复制该属性。

也许试试:

<NavBar location={this.props.router.location.pathname} onLogoutClick={logout}/>
 类似资料: