Jest and React Native: How to mock AccessibilityInfo

Viewed 725

I'm testing my react native app with Jest and the following line gives me an issue.

AccessibilityInfo.announceForAccessibility(errorMessages[0]);

Error:

TypeError: Cannot read property 'announceForAccessibility' of undefined

I've tried to mock it using

jest.mock('react-native', () => ({
  ...jest.requireActual('react-native'),
  AccessibilityInfo: {
    fetch: jest.fn(),
    addEventListener: jest.fn(),
    setAccessibilityFocus: jest.fn(),
    announceForAccessibility: jest.fn(),
    removeEventListener: jest.fn(),
  },
}));

but that brought a whole lot of other issues.

How could I mock this specific export on the react native package?

1 Answers

I had the same issue when using AccessibilityInfo.fetch() to determine if the user is using a screen reader.

One option for named imports is to use the spyOn method.

import { AccessibilityInfo } from 'react-native';

jest
  .spyOn(AccessibilityInfo, 'announceForAccessibility')
  .mockImplementation(...);
Related