在这里,我想改变状态并测试它。 我有
App.js 按顺序包含 3 个钩子:
const [searchResult, setSearchResult] = useState([]);
const [searched, setSearched] = useState('');
const [appsAlert, setAppsAlert] = useState({
success: { status: false, msg: '' },
error: { status: false, msg: '' },
});
在 utils.test.js 中
export const setHookState = (newState) =>
jest.fn().mockImplementation((state) => [newState, () => {}]);
在 App.test.js 中
import * as React from 'react';
import { mount } from 'enzyme';
import App from '../app';
import { setHookState } from '../../utils/test';
describe('Application Page Test Cases', () => {
beforeAll(() => {});
afterEach(() => {
jest.clearAllMocks();
});
test('Test Case 1', () => {
const reactMock = require('react');
reactMock.useState = setHookState({
searchResult: [],
searched: 'xyz',
appsAlert: {
success: { status: false, msg: 'Successful' },
error: { status: true, msg: 'Error Received' },
},
});
const wrapper = mount(<App />);
const searchBox = wrapper.find("[testId='AppListingSearchText']");
expect(searchBox.props().searched).toBe('xyz');
});
test('Test Case 2', () => {
const stateSetter = jest.fn();
jest
.spyOn(React, 'useState')
.mockImplementation((searched) => ['xyz', stateSetter]);
jest.spyOn(React, 'useState').mockImplementation((appsAlert) => [
{
success: { status: false, msg: '' },
error: { status: true, msg: 'Error Received' },
},
stateSetter,
]);
const wrapper = mount(<App />);
const searchBox = wrapper.find("[testId='AppListingSearchText']");
expect(searchBox.props().searched).toBe('xyz');
});
});
在这两个测试用例中,我希望搜索状态的值为“xyz”,但它显示以下错误: 应用程序页面测试用例 › 测试用例 1
TypeError: _react.default.useState is not a function
22 | });
23 |
> 24 | const wrapper = mount(<App />);
| ^
25 | expect(wrapper.props().searched).toBe('xyz');
我想测试状态更改为“xyz”的组件