I am trying to test (with Jest) an app's theme adapting to the phone system's theme. I am handling theses changes with the Appearance.getColorScheme()
helper from react-native.
If I am doing a simple test I have this error : TypeError: Cannot read property 'getColorScheme' of undefined
in my app, because when the app is running in the Jest env it can't access the native Appearance
data.
This is why I'm trying to mock the getColorScheme()
fn from the Appearance
helper to simply return 'light'
.
I've tried multiple solutions like the one in this question which was based on a different lib, not the react-native sub-module.
I've tried to use the mockComponent
fn provided by react-native
, then import the next snippet in my test :
// test/__mocks__/Appearance.js
import mockComponent from 'react-native/jest/mockComponent';
mockComponent('Appearance', {
getColorScheme: () => { return 'light' }
})
I get this error Cannot find module 'Appearance' from 'mockComponent.js'
.
I've tried this too, I think this is a wrong approach because it might mock react-native completely and it doesn't work :
// test/test.js
// Before the tests
import { Appearance } from 'react-native';
jest.mock('react-native', () => ({
Appearance: {
useColorScheme: jest.fn(),
}
}));
// And at the beginning of my test :
Appearance.useColorScheme.mockReturnValueOnce('dark');
Then I have this error TypeError: (0 , _reactNative.requireNativeComponent) is not a function
.
I've seen multiple solutions to mock an entire module, Date
or other methods found in window
for the web env. But I'm stuck to mock this particular sub-module from react-native.