是否不可能声明一些通过render
嵌套和react-testing-libary
其中之一的React函数组件?
这是我的尝试:
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")
})
})
然后jest test
朝我扔:
● 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 | })
任何帮助将不胜感激,谢谢!
答案 0 :(得分:1)
您在命名的导入中忘记了Id
;)