A small fix

Mocking revenuecat SDK for Jest tests in React-native

I recently integrated Revenuecat to codereader.dev, a react-native project. After I did it all of my Jest tests where failing. This was the error I was getting.

$ jest

 FAIL  __tests__/MyAppTest.tsx
  ● Test suite failed to run

    Invariant Violation: `new NativeEventEmitter()` requires a non-null argument.

      1 | import axios from 'axios';
      2 | import EncryptedStorage from 'react-native-encrypted-storage';
    > 3 | import Purchases from 'react-native-purchases';
        | ^
      4 | 

      at invariant (node_modules/invariant/invariant.js:40:15)
      at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:46:16)
      at Object.<anonymous> (node_modules/react-native-purchases/dist/purchases.js:45:20)
      at Object.<anonymous> (node_modules/react-native-purchases/dist/index.js:20:35)
      at Object.require (src/screens/Paywall.ts:5:1)
      at Object.require (src/screens/App.ts:6:1)
      at Object.require (__tests__/MyAppTest.tsx:3:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.314 s
Ran all test suites.
error Command failed with exit code 1.

As you can see, Jest is complaining because it cannot import Purchases from react-native-purchases. This happens because the Jest runtime does not has access to the native modules that react-native-purchases implements. Fortunately, the solution is easy. We just need to mock the import with the tools jest provides.

This small mock does it for me. In my case i was not using the Purchases SDK on my tests so i could actually put anything in there, that would've been enough to stop the native code to break our tests.

jest.mock('react-native-purchases', () => ({
  Purchases: {
    setup: jest.fn(),
    addPurchaserInfoUpdateListener: jest.fn(),
    removePurchaserInfoUpdateListener: jest.fn(),
    getOfferings: jest.fn(),
    purchasePackage: jest.fn(),
    restoreTransactions: jest.fn(),

Hope this helps anyone having issues with Jest on react-native because of the react-native-purchases package. The solution is quite small and easy to implement.

Written by Matias Andrade



Now Free

It‘s time to slay those downtimes.

download on play store