0Pricing
React Native Academy · Lesson

Mocking Native Modules and Async Code

Mock expo-location and other native modules in Jest setup files, use jest.fn() for callbacks, and test async flows with waitFor and findBy queries.

The Native Module Problem in Jest

Jest runs in a Node.js environment, not on a real device. When your component imports a native module like expo-camera or @react-native-async-storage/async-storage, Jest cannot execute the native code because there is no iOS or Android runtime available.

This causes tests to fail with errors like 'jest-environment-jsdom is not supported' or 'Cannot read property of undefined'. The solution is to mock native modules — replace them with JavaScript-only fakes that behave predictably in tests.

Manual Mocks in __mocks__ Folder

You can create a manual mock for any module by creating a file in the __mocks__ directory adjacent to node_modules. Jest automatically uses this mock whenever the module is imported in test files.

For example, create __mocks__/@react-native-async-storage/async-storage.js with a fake implementation that stores data in memory. The Expo and React Native communities maintain official mock packages for common native modules.

// __mocks__/@react-native-async-storage/async-storage.js
const storage = {};

export default {
  getItem: jest.fn((key) => Promise.resolve(storage[key] ?? null)),
  setItem: jest.fn((key, value) => {
    storage[key] = value;
    return Promise.resolve();
  }),
  removeItem: jest.fn((key) => {
    delete storage[key];
    return Promise.resolve();
  }),
  clear: jest.fn(() => {
    Object.keys(storage).forEach((k) => delete storage[k]);
    return Promise.resolve();
  }),
  getAllKeys: jest.fn(() => Promise.resolve(Object.keys(storage))),
};

All lessons in this course

  1. Setting Up Jest in a React Native Project
  2. Rendering Components with React Native Testing Library
  3. Firing Events and Testing User Interaction
  4. Mocking Native Modules and Async Code
← Back to React Native Academy