gpt4 book ai didi

reactjs - 在 Jest/React 中的 “store” 的上下文或 props 中找不到 “Connect(App)”

转载 作者:行者123 更新时间:2023-12-03 13:38:50 28 4
gpt4 key购买 nike

我正在尝试运行我的第一个 Jest 测试,但我的 react 文件的设置方式似乎存在问题:

应用程序测试:

it('renders without crashing', () => {
const app = shallow(<App />);
});

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);

index.js(嵌入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'));

他们说我对浅层渲染“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)".

enter image description here

我不确定还需要通过应用程序传递什么,或者是否需要将提供程序下移?

最佳答案

错误日志在这里清楚地表明您需要为您的组件提供一个存储。为此,您需要事先模拟您的商店,然后将其交给 <Provider />组件,包含 <App />作为 child 。您的文件应如下所示:

/* 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>
);
});

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

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

关于reactjs - 在 Jest/React 中的 “store” 的上下文或 props 中找不到 “Connect(App)”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57915595/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com