gpt4 book ai didi

reactjs - 使用 Jest react 单元测试失败

转载 作者:行者123 更新时间:2023-12-04 14:56:20 24 4
gpt4 key购买 nike

我正在用 jest 和 enzyme 做单元测试。我有以下带钩子(Hook)的连接组件。我调用了 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();
});
})

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

快照测试错误:

invariant violation element type is invalid: expected string or a class/function

方法调用测试错误:

Cannot read property 'loadData' of undefined.

Enzyme Internal error: Enzyme expects and adapter to be configured, but found none. ...

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

我正在使用 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 传递状态。此外,您需要配置 enzyme 。最后,当您使用 React Hooks 时,您将需要进行异步单元测试,因为效果是异步的。当您尝试检查是否调用了任何函数时,您需要“监视”它。

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' 更改为您的操作文件路径。最后,我不确定你使用的是什么中间件,所以请随意将 import createSagaMiddleware from 'redux-saga'; 替换为你的 redux 中间件。

关于reactjs - 使用 Jest react 单元测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67920606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com