Dar*_* Z. 5 javascript reactjs jestjs enzyme
如何使用 jest 在 React 测试中处理 localStorage。
我已添加到setupTest.js
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
removeItem: jest.fn(),
clear: jest.fn(),
};
global.localStorage = localStorageMock;
Run Code Online (Sandbox Code Playgroud)
这是我获取缓存的服务的示例:
export default class Cache {
getCache = () => {
return Promise.resolve(JSON.parse(localStorage.getItem('cache')));
}
}
Run Code Online (Sandbox Code Playgroud)
样本.test.js
import { mount } from 'enzyme';
import React from 'react';
import Component from '../Component';
const cacheData = JSON.stringify(require('../__mock__/data.json'));
// Trying to mock the function causing error _Cache.default .....
jest.mock('./Cache', () => {
return jest.fn().mockImplementation(() => {
return {
getCache: () => Promise.resolve(),
}
})
});
beforeAll(() => {
localStorage.setItem('cache', cacheDate);
});
describe("<Component /> ", () => {
it('set data to state', () => {
const wrapper = mount(<Component />);
wrapper.instance().getCache(); <-- my function in <Component /> to get data from cache service
wrapper.update();
console.log(wrapper.state()) <---- return null
})
})
Run Code Online (Sandbox Code Playgroud)
在<Component />componentDidMound循环中调用缓存服务来加载缓存,这里我期望测试中从localStorage获取数据。我一直在尝试另一种方法来做到这一点,但没有任何效果对我有用
| 归档时间: |
|
| 查看次数: |
2691 次 |
| 最近记录: |