- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 React hooks 功能组件,我想用 Jest/Enzyme 测试它。我想根据 useState 值测试其三级渲染行为。我似乎无法在网上找到任何示例。没有“点击”来模拟——没有 API 调用来模拟,因为最后,我仍然需要根据 useState 值进行测试。
过去,使用类组件,我可以设置状态。有了新的钩子(Hook),我不能。
所以,基本上 - 我如何在模拟的 submitForm 函数中模拟异步等待,以便渲染正常运行?
这是我的组件:
import React, { useState } from 'react';
import { Redirect } from 'react-router-dom';
import Form from 'core/Form';
export const Parent = ({submitForm}) => {
const [formValues, setFormValues] = useState({});
const [redirect, setRedirect] = useState(false);
const handleChange = name => evt => {
setFormValues({ ...formValues, [name]: evt.target.value });
};
const onSubmit = async () => {
try {
const res = await submitForm(formValues);
if (res) setRedirect(true);
else setRedirect(false);
} catch (err) {
console.log('Submit error: ', err);
}
};
return redirect ? (
<Redirect push to={path} />
) : (
<Form onSubmit={onSubmit} values={formValues} onChange={handleChange} />
);
};
export default Parent;
import React from 'react';
import { shallow } from 'enzyme';
import { Redirect } from 'react-router-dom';
import Parent from './Parent';
import Form from 'core/Form';
let wrapper, props;
.
.
.
describe('<Parent /> rendering', () => {
beforeEach(() => {
props = createTestProps();
wrapper = shallow(<Parent {...props} />);
});
afterEach(() => {
jest.clearAllMocks();
});
const setState = jest.fn();
const useStateSpy = jest.spyOn(React, 'useState');
useStateSpy.mockImplementation(init => [init, setState]);
it('Should render 1 Form', () => {
expect(wrapper.find(Form)).toHaveLength(1);
});
it('renders Redirect after API call', () => {
setRedirect = jest.fn(() => false);
expect(wrapper.find(Redirect)).toHaveLength(1);
});
it('renders Form before API call', () => {
setRedirect = jest.fn(() => true);
expect(wrapper.find(Form)).toHaveLength(1);
});
});
最佳答案
你不需要 spy useState
钩。这意味着您不应直接测试组件的这些钩子(Hook)和方法。相反,您应该测试组件的行为( state
、 props
以及呈现的内容)
例如。index.tsx
:
import React, { useState } from 'react';
import { Redirect } from 'react-router-dom';
export const Form = ({ onSubmit, onChange, values }) => <form onSubmit={onSubmit}></form>;
const path = '/user';
export const Parent = ({ submitForm }) => {
const [formValues, setFormValues] = useState({});
const [redirect, setRedirect] = useState(false);
const handleChange = (name) => (evt) => {
setFormValues({ ...formValues, [name]: evt.target.value });
};
const onSubmit = async () => {
try {
const res = await submitForm(formValues);
if (res) setRedirect(true);
else setRedirect(false);
} catch (err) {
console.log('Submit error: ', err);
}
};
return redirect ? (
<Redirect push to={path} />
) : (
<Form onSubmit={onSubmit} values={formValues} onChange={handleChange} />
);
};
export default Parent;
index.test.tsx
:
import Parent, { Form } from './';
import React from 'react';
import { shallow } from 'enzyme';
import { Redirect } from 'react-router-dom';
import { act } from 'react-dom/test-utils';
const whenStable = async () =>
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
describe('60137762', () => {
it('should render Form', () => {
const props = { submitForm: jest.fn() };
const wrapper = shallow(<Parent {...props}></Parent>);
expect(wrapper.find(Form)).toBeTruthy();
});
it('should handle submit and render Redirect', async () => {
const props = { submitForm: jest.fn().mockResolvedValueOnce(true) };
const wrapper = shallow(<Parent {...props}></Parent>);
wrapper.find(Form).simulate('submit');
await whenStable();
expect(props.submitForm).toBeCalledWith({});
expect(wrapper.find(Redirect)).toBeTruthy();
});
it('should handle submit and render Form', async () => {
const props = { submitForm: jest.fn().mockResolvedValueOnce(false) };
const wrapper = shallow(<Parent {...props}></Parent>);
wrapper.find(Form).simulate('submit');
await whenStable();
expect(props.submitForm).toBeCalledWith({});
expect(wrapper.find(Form)).toBeTruthy();
});
it('should handle error if submit failure', async () => {
const logSpy = jest.spyOn(console, 'log');
const mError = new Error('network');
const props = { submitForm: jest.fn().mockRejectedValueOnce(mError) };
const wrapper = shallow(<Parent {...props}></Parent>);
wrapper.find(Form).simulate('submit');
await whenStable();
expect(props.submitForm).toBeCalledWith({});
expect(logSpy).toHaveBeenCalledWith('Submit error: ', mError);
});
});
PASS stackoverflow/60137762/index.test.tsx
60137762
✓ should render Form (18ms)
✓ should handle submit and render Redirect (15ms)
✓ should handle submit and render Form (8ms)
✓ should handle error if submit failure (18ms)
console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
Submit error: Error: network
at /Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60137762/index.test.tsx:39:20
at step (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60137762/index.test.tsx:44:23)
at Object.next (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60137762/index.test.tsx:25:53)
at /Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60137762/index.test.tsx:19:71
at new Promise (<anonymous>)
at Object.<anonymous>.__awaiter (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60137762/index.test.tsx:15:12)
at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60137762/index.test.tsx:37:47)
at Object.asyncJestTest (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:100:37)
at resolve (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
at new Promise (<anonymous>)
at mapper (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
at promise.then (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 78.57 | 100 | 40 | 93.75 |
index.tsx | 78.57 | 100 | 40 | 93.75 | 12
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 4 passed, 4 total
Snapshots: 0 total
Time: 3.716s, estimated 5s
关于reactjs - 如何通过更改 useState 来测试 React Hooks 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60137762/
createHiveBackground 函数返回我要分配给状态的对象数组。稍后在我的应用程序中,我将使用 setHive 来更改数组的一些值。这些有什么区别? const [hive, setHiv
我很好奇为什么这么多程序员单独导入useState。 import React, { useState } from 'react'; const [foo, setFoo] = useState('
我已经设置了最基本的示例,即TODO列表当我第一次单击Done按钮时,它按预期工作:TODO项被标记为Done:True,并且“Fire”和“Setting”只触发一次。从那时起,我单击的任何按钮都会
我已经设置了最基本的示例,即TODO列表当我第一次单击Done按钮时,它按预期工作:TODO项被标记为Done:True,并且“Fire”和“Setting”只触发一次。从那时起,我单击的任何按钮都会
我正在尝试构建一个可以或不能接收查询字符串的代码。如果它收到所有查询字符串,我想执行一个函数: // state for query const [query, setQuery] = use
下面的代码有什么问题吗?使用 useState 时,我收到 typescript 警告 import * as React, { useState } from 'react' const useFo
我对此的反应是新的。我用每个开关元素创建了一个项目数组,问题是:当我单击一个项目时,所有项目都会同时激活!。我尝试了许多通过搜索找到的解决方案,但都不起作用。
我对此的反应是新的。我用每个开关元素创建了一个项目数组,问题是:当我单击一个项目时,所有项目都会同时激活!。我尝试了许多通过搜索找到的解决方案,但都不起作用。
我希望我没有重复一个问题。我看过这个:TypeError dispatcher.useState is not a function when using React Hooks ,但是我的应用程序运
当对状态、效果、上下文等使用钩子(Hook)时,我这样做: import React, { useState, useEffect, useContext } from 'react'; 但是,我注意
所以我试图在我的 nextjs 应用程序中使用 useState,但是一旦我添加了代码行来初始化 useState,它就会抛出一个带有错误消息的弹出错误:TypeError: Cannot read
我在单击表单提交按钮时使用 React useState 钩子(Hook)更新状态,直到第二次单击时状态才会更新。相信我需要使用 useEffect 但不确定如何使用 onClick 来实现。 con
是否可以从子组件内部更改 useState 的值? 家长: const [state, setState] = useState(false); return setState(true)}/> c
useState 不会立即更新状态。 我正在使用 react-select并且我需要根据请求的结果使用选择的 (multi) 选项加载组件。 出于这个原因,我创建了状态 defaultOptions
这个问题在这里已经有了答案: The useState set method is not reflecting a change immediately (15 个回答) 2年前关闭。 这是所有新
我想在触发正常函数 (handleConsultantChange) 后使用 useState 函数 (setFilterConsultantId) 更改状态 (filterConsultantId)
这是组件的完整代码,我累得想不出怎么解决这个问题 import React, { useEffect, useState } from 'react'; import { Link } from 'r
我正在尝试初始化一个常量变量,它可以用作字符串或字符串数组,具体取决于我的组件正在接收的 Prop 。 我正在尝试将其初始化为 const [selectedOptions, setSelecte
我有两个组件,一个放在另一个里面。子组件打印父组件传递的状态,并使用 useEffect 更新一次状态。在父组件中,我使用 setState(具有 bool 值的对象)并将状态传递给所有子组件。 父组
我们知道useState是FC中的一个hook,返回一个由两个元素组成的数组。第一个是状态变量,第二个是更新状态变量的函数。 const initialStateVariableValue = 0;
我是一名优秀的程序员,十分优秀!