我正在用Jest和Enzyme做本机反应的简单测试。目前,我正在测试和模拟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'
有帮助吗?谢谢!
答案 0 :(得分: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]);
});
}),
}));
答案 1 :(得分:-1)
您可以尝试在测试文件的beforeEach
中设置模拟,而不是在根级别设置setMock
beforeEach(() => {
const storageCache = {
'@token': '123sometoken987',
'@messages': 'this is a message'
};
jest.mock('AsyncStorage', () => new MockStorage(storageCache));
});