Skip to main content

Lesson 3 of 10

Mocking Device APIs in Tests

Tests run in a Node.js environment without a device. Device APIs (camera, location, haptics, AsyncStorage) must be mocked. Expo's jest-expo preset handles most automatic mocks; you add custom ones for your specific usage patterns.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Mocking expo and Device APIs

Mocking expo and Device APIs
// __mocks__/expo-location.ts
export const requestForegroundPermissionsAsync = jest.fn().mockResolvedValue({ status: 'granted' });
export const getCurrentPositionAsync = jest.fn().mockResolvedValue({
  coords: { latitude: 37.7749, longitude: -122.4194, accuracy: 5, altitude: null, heading: null, speed: null, altitudeAccuracy: null },
  timestamp: Date.now(),
});
export const Accuracy = { Balanced: 3, High: 5, Low: 1, Lowest: 1, BestForNavigation: 6, Best: 6 };

// __mocks__/@react-native-async-storage/async-storage.ts
// jest-expo provides this automatically, but for custom behavior:
import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock';
export default mockAsyncStorage;

// __mocks__/expo-haptics.ts
export const impactAsync = jest.fn().mockResolvedValue(undefined);
export const selectionAsync = jest.fn().mockResolvedValue(undefined);
export const notificationAsync = jest.fn().mockResolvedValue(undefined);
export const ImpactFeedbackStyle = { Light: 'light', Medium: 'medium', Heavy: 'heavy' };
export const NotificationFeedbackType = { Success: 'success', Warning: 'warning', Error: 'error' };

// ---- Using mocks in tests ----
import * as Location from 'expo-location';

test('shows user location on map', async () => {
  const mockCoords = { latitude: 51.5074, longitude: -0.1278 };
  (Location.getCurrentPositionAsync as jest.Mock).mockResolvedValueOnce({
    coords: { ...mockCoords, accuracy: 5 },
    timestamp: Date.now(),
  });

  const { findByTestId } = render(<MapScreen />);
  const marker = await findByTestId('user-location-marker');
  expect(marker).toBeTruthy();
});

// ---- MSW for API mocking ----
// npm install --save-dev msw
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';

const server = setupServer(
  http.get('https://api.example.com/posts', () => {
    return HttpResponse.json({ data: [{ id: '1', title: 'Test Post' }], total: 1, page: 1, hasNextPage: false });
  })
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('renders posts from API', async () => {
  render(<PostFeed />);
  expect(await screen.findByText('Test Post')).toBeTruthy();
});

Tip

Tip

Practice Mocking Device APIs in Tests in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Setting up global mocks for safe area, AsyncStorage, MMKV, and hardware sensors

Practice Task

Note

Practice Task - (1) Write a working example of Mocking Device APIs in Tests from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mocking Device APIs in Tests is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Topics in This Module

0/10 done