gpt4 book ai didi

javascript - React-Redux/Jest 不变违规 : Could not find "store"

转载 作者:数据小太阳 更新时间:2023-10-29 06:04:52 26 4
gpt4 key购买 nike

我设置了一个简单的测试文件,几乎与 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'));

我在这里忽略了什么?该应用程序可自行正常运行,但我终究无法弄清楚测试失败的原因。

最佳答案

使用您提交的代码,您应该不会出现您指定的错误。为了在不使用 Redux 装饰您的组件的情况下进行测试,您希望您的测试像这样导入您的 App 组件:

import { App } from './App'

你已经做到了!但是,您的测试输出看起来像您在某些时候确实有这样的结果:

import App from './App'

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

关于javascript - React-Redux/Jest 不变违规 : Could not find "store",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46537246/

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