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.
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;
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())
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With