简体   繁体   中英

Jest and React Native: How to mock AccessibilityInfo

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?

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(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM