使用jest的React Unit测试失败



我正在用jest和酶进行单元测试。我有下面的挂钩连接组件。我调用了redux操作来加载数据。

import React, {useEffect, useState, useCallBack} from "react";
import {connect} from "react-redux";
import CustomComponent  from "../Folder";
import { loadData, createData, updateData } from "../../redux/actions";
const AccountComponent = (props) => {
const total = 50;
const [aIndex, setAIndex] = useState(1);
const [arr, setArr] = useState(['ds,dsf']);
//... some state variables here
const getData = () => {
props.loadData(aIndex, total, arr);
}
useEffect(() => {
getData();
},[aIndex, total])
//some other useEffect and useCallback
return(
<React.Fragment>
<CustomComponent {...someParam}/>
<div>
...
</div>
</React.Fragment>
)
}
const mapStateToProps = (state) => {
const { param1, param2, parma3 } = state.AccountData;
return {
param1,
param2,
parma3
}
}
export default connect(mapStateToProps, { loadData, createData, updateData })(AccountComponent)

在这里,和下面一样,我为上面的组件创建了一些测试用例。

import AccountComponent from "../";
import React from "react";
import renderer from "react-test-renderer"
describe("AccountComponent component", () => {
const loadData = jest.fn();
let wrapper;
it("snapshot testing", () => {
const tree = renderer.create(<AccountComponent loadData={loadData} />).toJSON();
expect(tree).toMatchSnapshot();
})
beforeEach(() => {
wrapper = shallow(<AccountComponent loadData={loadData} />).instance();
});
it('should call loadData', () => {
expect(wrapper.loadData).toHaveBeenCalled();
});
})

但是,它没有通过并显示错误。

快照测试错误:

不变冲突元素类型无效:应为字符串或类/函数

方法调用测试错误:

无法读取未定义的属性"loadData"。

Enzyme内部错误:Enzyme需要配置和适配器,但未找到。。。

不确定是什么问题,因为我不擅长单元测试。

我正在使用react redux 7。

如有任何帮助,我们将不胜感激。

编辑:

我也尝试了类似以下的提供者。但是,没有帮助。

import { Provider } from "react-redux";
import {createStore} from "redux";
import reducer from "../../reducers";
const store = createStore(reducer);
it("snapshot testing", () => {
const tree = renderer.create(<Provider store={store}><AccountComponent loadData={loadData} /></Provider>).toJSON();
expect(tree).toMatchSnapshot();
})

beforeEach(() => {
wrapper = shallow(<Provider store={store}><AccountComponent loadData={loadData} /></Provider>).instance();
});

在您使用同一文件中的连接组件时,需要通过Provider传递状态。此外,你需要配置你的酶。最后,当您使用react钩子时,您将需要进行异步单元测试,因为效果是异步的。当你试图检查是否有任何函数被调用时,你需要";间谍;

import configureStore from 'redux-mock-store';
import React from 'react';
import renderer from 'react-test-renderer';
import Enzyme, { shallow } from 'enzyme';
import { Provider } from 'react-redux';
import Adapter from 'enzyme-adapter-react-16';
import { act } from 'react-dom/test-utils';
import createSagaMiddleware from 'redux-saga';
import AccountComponent from '../AccountComponent';
import * as actions from '../../../redux/actions';
jest.mock('../../../redux/actions', () => ({
loadData: jest.fn(),
createData: jest.fn(),
updateData: jest.fn(),
}));
const loadData = jest.spyOn(actions, 'loadData');
// configure Enzyme
Enzyme.configure({ adapter: new Adapter() });
const configureMockStore = configureStore([createSagaMiddleware]);
const initialState = {
AccountData: {
param1: 'param1',
param2: 'param2',
parma3: 'parma3 ',
},
};
const store = configureMockStore(initialState);
describe('AccountComponent component', () => {
let wrapper;
it('snapshot testing', () => {
const tree = renderer
.create(
<Provider store={store}>
<AccountComponent />
</Provider>,
)
.toJSON();
expect(tree).toMatchSnapshot();
});
beforeEach(async () => {
await act(async () => {
wrapper = shallow(
<Provider store={store}>
<AccountComponent />
</Provider>,
);
});
await act(async () => {
wrapper.update();
});
});
it('should call loadData', () => {
expect(loadData).toHaveBeenCalled();
});
});

请使用将在该组件中使用的属性模拟您的AccountData状态。此外,我不确定测试文件的位置,所以您可能需要将导入路径从'../../../redux/actions'更改为操作文件路径。最后,我不确定您使用的是什么中间件,所以请免费使用redux中间件替换import createSagaMiddleware from 'redux-saga';

如果你正在使用react,它已经随@testing-library一起提供了,你不需要酶来进行快照测试。这就是我进行快照测试的方式。

import React, { Suspense } from "react";
import { screen } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import AccountComponent from "../";
import store from "./store";// you can mock the store if your prefer too
describe("<AccountComponent />", () => {
test("it should match snapshot", async () => {
expect.assertions(1);
const { asFragment } = await render(
<Suspense fallback="Test Loading ...">
<Provider store={store}>
<AccountComponent />
</Provider>
</Suspense>
);
expect(asFragment()).toMatchSnapshot();
});
});

当它是一个功能组件并且您正在使用钩子时,单元测试可能无法使用浅层渲染。您必须使用"renderHooks"来创建包装。请参阅https://react-hooks-testing-library.com/了解更多详细信息。

相关内容

  • 没有找到相关文章

最新更新