Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem when testing a component with react-native-safe-area-context

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:

enter image description here

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>
like image 987
Filip Račić Avatar asked Jul 09 '26 00:07

Filip Račić


2 Answers

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.

like image 167
zackify Avatar answered Jul 11 '26 18:07

zackify


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),
  }
})
like image 40
Matheus Camara Avatar answered Jul 11 '26 18:07

Matheus Camara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!