【问题标题】:Cannot find module 'AsyncStorage' when testing with Jest/Enzyme使用 Jest/Enzyme 进行测试时找不到模块“AsyncStorage”
【发布时间】:2020-04-25 22:08:51
【问题描述】:

我正在使用 Jest 和 Enzyme 在 react-native 中进行简单的测试。目前我正在测试和模拟 AsyncStorage,但每次测试都失败了。我尝试将代码放入beforeEach(() => {}),但它也不起作用。检查下面的代码:

import 'react-native';
import React from 'react';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import MockStorage from '../../__mocks__/mockStorage';

const middlewares = [thunk]; 
const mockStore = configureStore(middlewares);

describe('testing AsyncStorage', () => {

    // Mock AsyncStorage
    const storageCache = {
        '@token': '123sometoken987',
        '@messages': 'this is a message'
    };

    const AsyncStorage = new MockStorage(storageCache);
    jest.setMock('AsyncStorage', AsyncStorage);
            ^ // fails here

    // ...
})

这是我的mockStorage.js:

export default class MockStorage {
    constructor(cache = {}) {
      this.storageCache = cache;
    }

    setItem = jest.fn((key, value) => {
      return new Promise((resolve, reject) => {
        return (typeof key !== 'string' || typeof value !== 'string')
            ? reject(new Error('key and value must be string'))
            : resolve(this.storageCache[key] = value);
         });
    });

    getItem = jest.fn((key) => {
      return new Promise((resolve) => {
        return this.storageCache.hasOwnProperty(key)
            ? resolve(this.storageCache[key])
            : resolve(null);
        });
    });

    removeItem = jest.fn((key) => {
      return new Promise((resolve, reject) => {
        return this.storageCache.hasOwnProperty(key)
            ? resolve(delete this.storageCache[key])
            : reject('No such key!');
        });
    });

    clear = jest.fn((key) => {
        return new Promise((resolve, reject) =>  resolve(this.storageCache = {}));
    });

    getAllKeys = jest.fn((key) => {
        return new Promise((resolve, reject) => resolve(Object.keys(this.storageCache)));
    });
  }

测试失败并出现以下错误:

无法从“myFileName.js”中找到模块“AsyncStorage”

有什么帮助吗?谢谢!

【问题讨论】:

    标签: reactjs react-native jestjs enzyme


    【解决方案1】:

    对于那些仍在寻找的人来说,这对我有用。模拟整个 react-native 模块不起作用,但提供 AsyncStorage 模块的路径可以。

    const mockItems = {};
    jest.mock('react-native/Libraries/Storage/AsyncStorage', () => ({
        setItem: jest.fn((item, value) => {
            return new Promise((resolve, reject) => {
                mockItems[item] = value;
                resolve(value);
            });
        }),
        getItem: jest.fn((item) => {
            return new Promise((resolve, reject) => {
                resolve(mockItems[item]);
            });
        }),
    }));
    

    【讨论】:

    • 谢谢!刚挖了一整天,终于解决了这个问题。这对于在 React Native 和 Expo 上使用 AsyncStorage 的任何人都很有用(目前还不支持新的 @react-native-community/AsyncStorage)
    【解决方案2】:

    您可以尝试在测试文件中的beforeEach 中设置模拟,而不是在根级别设置setMock

    beforeEach(() => {
      const storageCache = {
        '@token': '123sometoken987',
        '@messages': 'this is a message'
      };
    
      jest.mock('AsyncStorage', () => new MockStorage(storageCache));
    });
    

    【讨论】:

    • 我遇到了一个巨大的错误:babel-plugin-jest-hoist: The module factory of "jest.mock()" is not allowed to reference any out-of-scope variables. Invalid variable access: storageCache@colinux
    • 尝试将storageCache 对象直接移动到new MockStorage 内部:new MockStorage({ '@token': "..." })
    • 它抛出了同样的错误Cannot find module "AsyncStorage"...。顺便说一句,您的答案中缺少)。 @colinux
    • 你是如何在你的测试文件中导入AsyncStorage 的?
    • import AsyncStorage from '@react-native-community/async-storage',但我的代码或您的代码都没有使用导入。我的问题是我是如何实施的。 @colinux
    猜你喜欢
    • 2016-10-30
    • 1970-01-01
    • 2018-11-09
    • 2020-12-17
    • 2017-03-20
    • 2019-07-28
    • 2019-10-30
    • 2022-06-12
    • 2019-10-26
    相关资源
    最近更新 更多