I have one component with Redux useSelector, when I want to test the render text, it shows error message on useSelector and with the error message: could not find react-redux context value; please ensure the component is wrapped in a <Provider>. I have put <Provider> to the top level component, where is the wrong part on my testing code? The app itself is running correct.
TopLevel component:
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
import { Provider } from "react-redux"
import store from "./redux/store"
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("test")
)
App.js
import { useEffect, useState, useCallback } from "react"
import { useDispatch, useSelector } from "react-redux"
import { fetchPosts, showName } from "./redux/actions/posts"
import Main from "./component/main"
function App() {
const { posts, name } = useSelector((state) => state.posts)
const dispatch = useDispatch()
const handleClick = useCallback(() => {
dispatch(fetchPosts())
}, [])
const handleShowName = useCallback((textName) => {
dispatch(showName(textName))
}, [])
return (
<div className="App" data-test="appComponent">
<button onClick={handleClick}>get post</button>
<button onClick={() => handleShowName("test")}>Show name</button>
<section className="main">
<div>project name: {name}</div>
<Main posts={posts} />
</section>
</div>
)
}
export default App
app.test.js
import React from "react"
import App from "./App"
import { render, fireEvent, screen } from "@testing-library/react"
it("render a div with text 'project name'", () => {
const { container, getByText } = render(<App />)
expect(getByText("project name:")).toBeInTheDocument()
})
When I test my redux action and redux reducer, my testing is working. So the Jest setting should be fine.
jest.config.js
module.exports = {
setupFilesAfterEnv: ["./setupTests.js"]
}
setupTest.js
import '@testing-library/jest-dom/extend-expect';
babel.config.js
module.exports = {
presets: ["@babel/preset-env", "@babel/preset-react"],
plugins: [
["@babel/plugin-proposal-class-properties", { loose: false }],
[
"@babel/plugin-transform-runtime",
{
corejs: 3,
helpers: true,
regenerator: true
}
]
]
}