react-test-library 呈现在测试中声明的功能组件

react-test-library render a functional component that is declared in the test

是否无法通过 react-testing-libary 声明一些嵌套的 React 函数组件和 render 其中之一?

这是我的尝试:

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

任何帮助将不胜感激,谢谢!

您在指定的导入中忘记了 Id ;)