我已经编写了此组件。它使用钩子和状态获取数据。提取后,加载状态将更改为false并显示侧边栏。
我遇到了Jest和Enzyme的问题,因为它在我的单元测试中确实对act发出警告。一旦将动作添加到我的笑话和酶中,测试就会失败!
// @flow
import React,{ useEffect,useState } from 'react';
import Sidebar from '../components/Sidebar';
import fetchData from '../apiWrappers/fetchData';
const App = () => {
const [data,setData] = useState([]);
const [loading,setLoading] = useState(true);
useEffect(() => {
const getData = async () => {
try {
const newData = await fetchData();
setData(newData);
setLoading(false);
}
catch (e) {
setLoading(false);
}
};
getData();
// eslint-disable-next-line
},[]);
return (
<>
{!loading
? <Sidebar />
: <span>Loading List</span>}
</>
);
};
export default App;
而且,我添加了一个这样的测试,该测试非常有效。
import React from 'react';
import { mount } from 'enzyme';
import fetchData from '../apiWrappers/fetchData';
import data from '../data/data.json';
import App from './App';
jest.mock('../apiWrappers/fetchData');
const getData = Promise.resolve(data);
fetchData.mockReturnValue(getData);
describe('<App/> Rendering using enzyme',() => {
beforeEach(() => {
fetchData.mockClear();
});
test('After loading',async () => {
const wrapper = mount(<App />);
expect(wrapper.find('span').at(0).text()).toEqual('Loading List');
const d = await fetchData();
expect(d).toHaveLength(data.length);
wrapper.update();
expect(wrapper.find('span').exists()).toEqual(false);
expect(wrapper.html()).toMatchsnapshot();
});
});
所以,我得到了警告:
Warning: An update to App inside a test was not wrapped in act(...).
When testing,code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
我确实使用{act} react-dom / test-utils解决了这种警告。
import React from 'react';
import { act } from 'react-dom/test-utils';
import { mount } from 'enzyme';
import fetchData from '../apiWrappers/fetchData';
import data from '../data/data.json';
import App from './App';
jest.mock('../apiWrappers/fetchData');
const getData = Promise.resolve(data);
fetchData.mockReturnValue(getData);
describe('<App/> Rendering using enzyme',async () => {
await act(async () => {
const wrapper = mount(<App />);
expect(wrapper.find('span').at(0).text()).toEqual('Loading List');
const d = await fetchData();
expect(d).toHaveLength(data.length);
wrapper.update();
expect(wrapper.find('span').exists()).toEqual(false);
expect(wrapper.html()).toMatchsnapshot();
});
});
});
但是,然后我的测试失败了。
<App/> Rendering using enzyme › After loading
expect(received).toEqual(expected) // deep equality
Expected: false
Received: true
35 |
36 | wrapper.update();
> 37 | expect(wrapper.find('span').exists()).toEqual(false);
有人知道为什么失败吗?谢谢!
"react": "16.13.1","enzyme": "^3.11.0","enzyme-adapter-react-16": "^1.15.3",