React-Redux / Jest Invariant Violation:找不到" store"

时间:2017-10-03 04:30:56

标签: javascript reactjs react-redux jestjs create-react-app

我有一个简单的测试文件设置,几乎与create-react-app使用的文件相同:

App.test.js

import React from 'react';
import ReactDOM from 'react-dom';
import { App } from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
});

当我运行yarn test时,我不断收到此错误消息:

Invariant Violation: Could not find "store" in either the context or props of "Connect(App)". Either wrap the root component in a <Provider>, or explicitly pass "st ore" as a prop to "Connect(App)".

我尝试在我的App.js文件中执行单独的导出并导入非Redux组件,但我仍然无法使其工作。以下是我涉及的另外两个文件:

App.js

import React, { Component } from 'react';
import axios from 'axios';
import { connect } from 'react-redux';

import TableList from './containers/table_list';
import Header from './components/header';
import Footer from './components/footer';

import './style/App.css';

// use named export for unconnected component (for tests)
export class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      recentUsers: [],
      allTimeUsers: []
    }
  }

  componentWillMount() {
    axios.all([this.fetchRecentUsers(), this.fetchAllTimeUsers()])
      .then(axios.spread((recentUsers, allTimeUsers) => {
        this.setState({ recentUsers: recentUsers.data, allTimeUsers: allTimeUsers.data });
    }))
      .catch((error) => {
        console.log(error)
      });
  }

  fetchRecentUsers() {
    return axios.get(RECENT);
  }

  fetchAllTimeUsers() {
    return axios.get(ALLTIME);
  }

  render() {
    return (
      <div>
        <Header />
          <div className="container">
            <TableList users={this.state.recentUsers} />
          </div>
        <Footer />
      </div>
    )
  }
}

const mapStateToProps = state => (
  { recentUsers: state.recentUsers, allTimeUsers: state.allTimeUsers }
)

// use default export for the connected component (for app)
export default connect(mapStateToProps)(App);

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';

import rootReducer from './reducers/index';
import App from './App';
import './style/index.css';

const store = createStore(rootReducer);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>, document.getElementById('root'));

我在这里俯瞰什么?该应用程序可以自行运行,但我无法弄清楚为什么测试失败。

1 个答案:

答案 0 :(得分:6)

使用您提交的代码,您不应该有您指定的错误。为了在不使用Redux修饰您的组件的情况下进行测试,您希望测试导入App组件,如下所示:

import { App } from './App'

你已经做过了!但是,测试的输出看起来像是在某些时候确实如此:

import App from './App'

请再次检查,确保您保存了测试文件等......