'Cannot destructure property 'desks' of '(0 , _react.useContext)(...)' as it is undefined
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?
Solution 1:[1]
Just use the provider in the render and no need to mock, it's working!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mathdx |
