Skip to main content
Glama
mocking.md2.66 kB
--- title: Mocking native calls in Expo modules sidebar_title: Mocking native calls description: Learn about mocking native calls in Expo modules. --- The recommended way to write unit tests for an Expo project is to use [Jest](https://jestjs.io/) and the `jest-expo` preset. To write a unit test for an app that uses native code, you need to mock native calls. The term **Mocking** means to replace the actual implementation of a function with a fake version that does not perform any actions. This approach is useful for running unit tests on a local computer as it involves bypassing the need for native code which is only available on a device, and any code that calls native functions on a local machine will not work. Expo SDK includes a set of default mocks for each of our community packages. You can also mock any JS code yourself using built-in Jest APIs such as [mock functions](https://jestjs.io/docs/mock-functions). However, to provide default mocks in your Expo Module, we offer a method to bundle them. This ensures that when your module user runs unit tests, they will automatically use a mocked implementation. ## Providing mocks for a module Create a file with the same name as the native module you want to mock and place it in your module's **mocks** directory. Make sure to export the mock implementation from this file. The `jest-expo` preset will automatically return the exported functions because of a `requireNativeModule` call when running during a unit test. For example, the `expo-clipboard` library has a native module called `ExpoClipboard`. You will create a **ExpoClipboard.ts** in the **mocks** directory to mock it. ```ts ExpoClipboard.ts return false; } ``` Now, in a unit test, calling `ExpoClipboard.hasStringAsync()` returns `false`. ## Automatic generation of mocks Maintaining mocks for native modules can be a lot of work if the native module has multiple methods. To make this easier, we provide a script that automatically generates mocks for all native functions in a module. It works for generating mocks in TypeScript and JavaScript based on the Swift implementation in your module. To use this script, you have to install [SourceKitten](https://github.com/jpsim/SourceKitten) framework. Then, navigate to the module directory (where your module's **expo-module.config.json** is located) and run the `generate-ts-mocks` command. The command above generates **ExpoModuleName.ts** in the **mocks** directory of your module. It contains a mock implementation for each native method and view in your module. > **Tip:** You can also run `generate-js-mocks` to generate mocks in JavaScript. ## More

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/jaksm/expo-docs-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server