I have a problem when trying to test a component with react-native-safe-area-context,
Test file:
import _ from "lodash"
import React from "react"
import mockSafeAreaContext from "react-native-safe-area-context/jest/mock"
import renderer from "react-test-renderer"
import CeoHeader from "../../src/screens/assessment/board/ceo_review/header"
jest.mock("react-native-safe-area-context", () => mockSafeAreaContext)
let props
beforeEach(() => {
props = {
onBack: jest.fn(),
firstOrLastPage: _.sample([true, false]),
onRefresh: jest.fn(),
}
})
describe("<CeoHeader />", () => {
it("has 1 child", () => {
const tree = renderer.create(<CeoHeader {...props} />).toJSON()
expect(tree.children).toHaveLength(1)
})
})
Error:

SafeAreaProvider is rendered at the top of the app
<Root>
<LoadingOverlay loading={loadingRdirectAction} />
<SafeAreaProvider
initialMetrics={{
frame: { x: 0, y: 0, width: 0, height: 0 },
insets: { top: 0, left: 0, right: 0, bottom: 0 },
}}
>
<AppNavigator />
</SafeAreaProvider>
</Root>
Here's a much simpler way to mock this. It is described in the library's documentation:
import mockSafeAreaContext from 'react-native-safe-area-context/jest/mock';
jest.mock('react-native-safe-area-context', () => mockSafeAreaContext);
Put this in your test or jest setup file.
Found a solution here:
https://github.com/th3rdwave/react-native-safe-area-context/issues/31
This is how it worked for me:
jest.mock('react-native-safe-area-context', () => {
const inset = { top: 0, right: 0, bottom: 0, left: 0 }
return {
SafeAreaProvider: jest.fn().mockImplementation(({ children }) => children),
SafeAreaConsumer: jest
.fn()
.mockImplementation(({ children }) => children(inset)),
useSafeAreaInsets: jest.fn().mockImplementation(() => inset),
}
})
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