gpt4 book ai didi

reactjs - useSelector 未定义

转载 作者:行者123 更新时间:2023-12-03 14:22:23 24 4
gpt4 key购买 nike

嗨,我正在为一个包含 redux 的组件编写单元测试。在测试它时,抛出错误 UseSelector state undefined。 UseSelector 将在收到 api 响应后更新一次。直到它的值是未定义的。但是,在进行单元测试时,它会在第一个本身上引发错误。如何克服这个问题。

测试文件

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { act } from 'react-dom/test-utils';
import '@testing-library/jest-dom/extend-expect';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import LinkApplication from '../index';
import {reducer} from '../../../redux/summary/reducer';
let INITIAL_STATES = {
isFetching: false,
errorMessage: "",
requestExtensionErrorMessage: "",
requestExtensionSuccessMessage: "",
linkApplicationSuccess: "",
linkApplicationFailure: null,
linkLoanSuccessMessage: "",
linkLoanErrorMessage: "",
LinkApplicationErrorMessage:"",
};
function renderWithRedux(
component,
{ INITIAL_STATES, store = createStore(reducer, INITIAL_STATES) } = {},
) {
return {
...render(<Provider store={store}>{component}</Provider>),
};
}
it('sumbits the form', async () => {
const onSubmit = jest.fn();
const { getByText, getByTestId } = renderWithRedux(
<LinkApplication onSubmit={onSubmit} />,
);
const Dob_Input = getByTestId('dob-input');
const Phone_Input = getByTestId('phone-input');
const form = getByTestId('form');
act(() => {
fireEvent.keyPress(Dob_Input, {
target: { value: '1995-09-27' },
});
fireEvent.keyPress(Phone_Input, { target: { value: '9500902621' } });
});
expect(Dob_Input.value).toBe('1995-09-27');
expect(Phone_Input.value).toBe('9500902621');
await act(() => {
fireEvent.submit(form);
});
expect(onSubmit).not.toHaveBeenCalled();
})

组件

const LinkApplication = () => {
const dispatch = useDispatch();
let LinkApplicationErrorMessage = useSelector(
state => state.summary.linkApplicationFailure
);
}

错误

TypeError: Cannot read property 'linkApplicationFailure' of undefined
const dispatch = useDispatch();
let LinkApplicationErrorMessage = useSelector(
state => state.summary.linkApplicationFailure
^
);

请帮我解决这个问题。

最佳答案

我认为你需要模拟react-redux

import * as React from 'react';
import { shallow } from 'enzyme';
jest.mock('react-redux', () => ({
useDispatch: () => {},
useSelector: () => ({
your: 'state',
}),
}));
import Component from './index';
describe('Test component', () => {
it('Should render and match the snapshot', () => {
const wrapper = shallow(<Component />);
});
});

关于reactjs - useSelector 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60668240/

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