0

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!

Norfeldt
  • 5,230
  • 13
  • 70
  • 118

1 Answers1

2

You forgot an Id in the named imports ;)

Giorgio Polvara - Gpx
  • 12,268
  • 5
  • 53
  • 55