I am trying to mock the useColorScheme hook from react native so I can control what values it returns. My code is below:
const mockColorScheme = jest.fn();
jest.mock('react-native/Libraries/Utilities/useColorScheme', () => ({
useColorScheme: mockColorScheme,
}));
it('Renders correct theme when user selects light', () => {
const wrapper = ({children}: any) => (
<ThemeProvider userIsUsingDarkMode={false} userIsUsingSystemTheme={false}>
{children}
</ThemeProvider>
);
const {result} = renderHook(() => useTheme(), {wrapper});
expect(result.current.theme).toBeDefined();
expect(result.current.theme?.text).toStrictEqual('#333');
mockColorScheme.mockImplementationOnce(() => 'dark');
expect(result.current.theme).toBeDefined();
expect(result.current.theme?.text).toStrictEqual('#fbfbfb');
});
I would expect this to work, but I get the following error:
TypeError: (0 , _reactNative.useColorScheme) is not a function
This comes from my ThemeProvider component:
export const ThemeProvider: FunctionComponent<ThemeProviderProps> = ({
children,
userIsUsingDarkMode,
userIsUsingSystemTheme,
}) => {
const isDarkMode = useColorScheme() === 'dark';
...
export const useTheme = () => {
return useContext(ThemeContext);
};
If anyone has any ideas as to how to mock this I would really appreciate it. Thank you.
We could simply mock the module default export.
const mockedUseColorScheme = jest.fn();
jest.mock('react-native/Libraries/Utilities/useColorScheme', () => {
return {
default: mockedUseColorScheme,
};
});
I was struggled for hours to solve the same problem, and I think I found a solution. All you have to do is to mock actual module for the hook.
const mockedColorScheme = jest.fn()
jest.mock("react-native/Libraries/Utilities/useColorScheme", ()=> ({
...jest.requireActual("react-native/Libraries/Utilities/useColorScheme"),
useColorScheme: mockedColorScheme
}))
it("renders useColorScheme hook with return value of 'dark'", () => {
mockedColorScheme.mockImplementationOnce(() => "dark")
const { result } = renderHook(() => mockedColorScheme())
expect(result.current).toBeDefined()
expect(result.current).toEqual("dark")
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With