I have a React project. In this project we are using some SDK to handle authentication-related activities. This SDK is imported in almost all the components. This SDK has other internal dependencies.
import { exampleSDK } from "../../path/exampleSDK";
const exampleComponent = () => {
const { onAuthenticate, onLogout } = exampleSDK({}) // just few examples
return (<><div>Example Component</div>/</>)
}
This exampleSDK
has internal dependencies which seem to be failing when I'm trying to call the components in my unit tests. I don't have to write the unit test for the SDK. I want to be able to mock the implementation of the exampleSDK
while testing the components. currently, I'm getting the following error when I'm calling the component with render()
function from "@testing-library/react"
.
TypeError: Cannot read properties of undefined (reading 'y')
> 12 | ExampleHandler.prototype = Object.create(window.x.y.prototype)
^
This is implemented in a module which is being called inside the exampleSDK
.
I tried using the Object.defineProperty(window, 'x', {y: {}})
but that didn't work(maybe I'm doing it wrong).
Is there a way to skip the error part or if it is possible to mock the implementation of the SDK?
If you want to mock your SDK you can do so by jest.mock()
. Try this out in your test
jest.mock('../../path/exampleSDK', () => ({
exampleSDK: (args) => {
// Return some values such as:
return {
onAuthenticate: jest.fn(),
onLogout: jest.fn()
};
}
}));
test('your test description', () => {
// Write your test here
})
There are more than 1 way to mock. Above is just one of them.
You can check out jest.spyOn()
or .mockImplementation()
or .mockReturnValue()
Search for these things on the jest docs - https://jestjs.io/docs/mock-function-api