【问题标题】:RNEncryptedStorage is undefined while running testing-library/react-native with Jest使用 Jest 运行 testing-library/react-native 时 RNEncryptedStorage 未定义
【发布时间】:2021-08-27 02:41:16
【问题描述】:

我正在尝试使用 react-native-testing-library 和 Jest 设置我的 react-native 测试环境。我的 react-native 应用程序使用 react-native-encrypted-storage。当我运行我的第一个示例测试(下面的代码)时,它说 RNEcryptedStorage 未定义。

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 />);
});

完全错误:

RNEncryptedStorage 未定义

在对象。 (node_modules/react-native-encrypted-storage/lib/commonjs/EncryptedStorage.ts:7:9) 在对象。 (node_modules/react-native-encrypted-storage/lib/commonjs/index.ts:1:1)

这是我第一次设置我的测试环境,所以不知道从哪里开始解决这个问题。

【问题讨论】:

  • 你做到了吗?
  • @HradeshKumar 不,我放弃了这种测试方式,因为大多数服务/功能都需要被嘲笑,据我说不会给出真正的测试结果

标签: react-native jestjs react-native-testing-library


【解决方案1】:

您可以在测试期间通过将react-native 模拟添加到您的__mocks__ 文件夹来模拟RNEncryptedStorage 本机模块。

// 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())
        }
    }
}
【解决方案2】:

上述方法可行,但如果您模拟 react-native 的其他方面,则可能会与其他模拟产生问题。如果您想自己模拟 RNEncryptedStorage,您可以尝试对上述解决方案稍作改动:

__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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-08
    • 2019-10-13
    • 2023-02-20
    • 1970-01-01
    • 2020-04-13
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多