简体   繁体   中英

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

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!

You forgot an Id in the named imports;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM