Could not find “store” in either the context or props of “Connect(App)” in Jest/React

los*_*193 5 reactjs jestjs

I'm trying to run my first jest test but it seems like there's an issue with the way my react files are set up:

app_test:

it('renders without crashing', () => {
  const app = shallow(<App />);
});
Run Code Online (Sandbox Code Playgroud)

app.js

class App extends Component {
  componentWillMount() {
    this.fetchUserAccountInfo();
  }

  render() {
    return <MainRoutes auth={this.props.loggedIn} />;
  }
}

function mapStateToProps(state) {
  return {
    loggedIn: state.loggedIn.userLoggedIn,
  };
}

export default connect(
  mapStateToProps,
  { fetchUserAccountInfo }
)(App);
Run Code Online (Sandbox Code Playgroud)

index.js (embeds App.s)

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers);
const token = localStorage.getItem("token");
const bugsnagClient = bugsnag({...//bugsnag stuff})

bugsnagClient.use(bugsnagReact, React);
const ErrorBoundary = bugsnagClient.getPlugin("react");

const RootApp = () => (
  <ErrorBoundary>
    <Provider store={store}>
      <App id={token} />
    </Provider>
  </ErrorBoundary>,
);

ReactDOM.render(<RootApp />, document.getElementById('.app'));
Run Code Online (Sandbox Code Playgroud)

They say i have an issue with shallow rendering "App"

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 "store" as a prop to "Connect(App)".
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

I'm not sure what else I need to pass through App or if I need to move the Provider down?

Orl*_*yyn 2

错误日志在这里清楚地表明您需要为您的组件提供一个存储。为此,您需要事先模拟您的商店,然后将其提供给<Provider />包含<App />as 子级的组件。你的文件应该是这样的:

/* app_test */

import React from 'react';
import { shallow } from 'enzyme';
import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import App from './App';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

it('renders without crashing', () => {
  const store = mockStore({}); // Instead of {}, you can give your initial store
  shallow(
    <Provider store={store}>   // Provides the store to your App
      <App />
    </Provider>
  );
});

Run Code Online (Sandbox Code Playgroud)

这段代码应该可以解决问题!

欲了解更多信息,您可以查看此页面:https ://redux.js.org/recipes/writing-tests