Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RNEncryptedStorage is undefined while running testing-library/react-native with Jest

Tags:

I am trying to setup my react-native test environment with react-native-testing-library and Jest. My react-native application uses react-native-encrypted-storage. When I run my first sample test (code below) it fails saying RNEcryptedStorage is undefined.

import React from "react";
import "react-native";
// Note: test renderer must be required after react-native.
import renderer from "react-test-renderer";
import App from "../App";
    
it("renders correctly", () => {
    console.log("Rendering");
    renderer.create(<App />);
});

Full error:

RNEncryptedStorage is undefined

at Object. (node_modules/react-native-encrypted-storage/lib/commonjs/EncryptedStorage.ts:7:9) at Object. (node_modules/react-native-encrypted-storage/lib/commonjs/index.ts:1:1)

This is first time I am setting up my test environment so not sure where do I start for resolving this issue.

like image 1000
me_digvijay Avatar asked Jun 10 '21 05:06

me_digvijay


2 Answers

The above will work, but if you mock other aspects of react-native it could create a problem with the other mocks. If you want to mock RNEncryptedStorage on its own, you could try a slight variation of the above solution:

__mocks__/react-native-encrypted-storage/index.js


const RNEncryptedStorage = {
  setItem: jest.fn(() => Promise.resolve()),
  getItem: jest.fn(() => Promise.resolve('{ "foo": 1 }')),
  removeItem: jest.fn(() => Promise.resolve()),
  clear: jest.fn(() => Promise.resolve()),
};

export default RNEncryptedStorage;

like image 101
ccfz Avatar answered Oct 10 '22 20:10

ccfz


You can mock the RNEncryptedStorage native module during your tests by adding a react-native mock to your __mocks__ folder.

// tests/__mocks__/react-native.js

module.exports = {
    NativeModules: {
        RNEncryptedStorage: {
            setItem: jest.fn(() => Promise.resolve()),
            getItem: jest.fn(() => Promise.resolve('{ "foo": 1 }')),
            removeItem: jest.fn(() => Promise.resolve()),
            clear: jest.fn(() => Promise.resolve())
        }
    }
}
like image 39
juliomalves Avatar answered Oct 10 '22 20:10

juliomalves