Reputation: 9678
Is it not possible to declare some react function components that nest and render
one of them via the react-testing-libary
?
Here is my attempt:
RestaurantIdContext.js
import React from "react"
const RestaurantIdContext = React.createContext(null)
export const RestaurantIdProvider = RestaurantIdContext.Provider
export const RestaurantIdConsumer = RestaurantIdContext.Consumer
export default RestaurantIdContext
RestaurantIdContext.test.js
import React, { useContext } from "react"
import { render } from "@testing-library/react"
import "@testing-library/jest-dom/extend-expect"
import RestaurantIdContext, { RestaurantProvider, RestaurantConsumer } from "./RestaurantIdContext"
describe("RestaurantIdContext", () => {
it("makes it possible to get the restaurant ID", () => {
function NestedComponent() {
const restaurantId = useContext(RestaurantIdContext)
return <p>Restaurant ID: {restaurantId}</p>
}
function GreatGrandParentComponent() {
return (
<div>
<RestaurantProvider value="123456">
<div>
<div>
<NestedComponent />
</div>
</div>
</RestaurantProvider>
</div>
)
}
const { getByText } = render(<GreatGrandParentComponent />)
expect(getByText("Restaurant ID").textContent).toBe("Restaurant ID: 123456")
})
})
Then jest test
throws this at me:
● RestaurantIdContext › makes it possible to get the restaurant ID
Invariant Violation: Element type is invalid: expected a string (for built-in compo
nents) or a class/function (for composite components) but got: undefined. You likely fo
rgot to export your component from the file it's defined in, or you might have mixed up
default and named imports.
Check the render method of `GreatGrandParentComponent`.
26 | }
27 |
> 28 | const { getByText } = render(<GreatGrandParentComponent />)
| ^
29 |
30 | expect(getByText("Restaurant ID").textContent).toBe("Restaurant ID: 123456")
31 | })
Any help will be appreciated, thank you!
Upvotes: 0
Views: 1404