Edit this page
Learn about mocking native calls in Expo modules.
The recommended way to write unit tests for an Expo project is to use Jest 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.
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.
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.
export async function hasStringAsync(): Promise<boolean> {
return false;
}
Now, in a unit test, calling ExpoClipboard.hasStringAsync()
returns false
.
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 framework and run the generate-ts-mocks
command in your module.
-
brew install sourcekitten
-
npx expo-modules-test-core generate-ts-mocks
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.
Learn how to set up and configure the jest-expo package to write unit and snapshot tests for a project.