Cannot destructure property 'desks' of '(0 , _react.useContext)(...)' as it is undefined

Viewed 1124

I try to mock DeskContext for having desks and checkIfUserPresent when useContext is called. But I have this error:

Cannot destructure property 'desks' of '(0 , _react.useContext)(...)' as it is undefined
TypeError: Cannot destructure property 'desks' of '(0 , _react.useContext)(...)' as it is undefined.

This is when I run this test:

it('It should have a reserved button because user is not present', () => {
render(<Desk desk={deskWithNoReservation} dateOfConsultation={dateInTheFuture()}/>)

        const buttonElement = screen.getByText('Réserver')
    
        expect(buttonElement).toBeInTheDocument()
    })

Here is my code:

...
jest.mock('../context/DeskContext', () => ({
DeskContext:{
   desks: [{
      deskNumber: 11,
      reservation: "mocked name"
   }],
   checkIfUserPresent: () => {
      return false
   },
}
}))

jest.mock('./ModalWindow', () => ({ ModalWindow: () => 'Réserver' }));

describe('Test for Desk component', () => {

    it('It should have a reserved button because user is not present', () => {
        render(<Desk desk={deskWithNoReservation} dateOfConsultation={dateInTheFuture()}/>)
    
        const buttonElement = screen.getByText("Réserver")
    
        expect(buttonElement).toBeInTheDocument()
    })

...

In my class 'DeskComponent', this is the line (the first one of the component) that cause the error: "const {desks, checkIfUserPresent} = useContext<any>(DeskContext)"

Here is DeskContext class:

import { createContext } from "react"

export const DeskContext = createContext({})

Do you know what to do to define desks and checkIfUserSPResent for further code? Thanks.

To define desks and checkIfUserSPResent for passing the test?

2 Answers

Just use the provider in the render and no need to mock, it's working!

You have to wrap the desk object with the provider in the render, so yours would be something like

    render(<DeskProvider><Desk desk={deskWithNoReservation} dateOfConsultation={dateInTheFuture()}/><DeskProvider/>)
Related