reactjs - “React 检测到 Hook 的顺序发生了变化”
问题描述
我在为 Auth 组件编写测试时遇到了这个问题。不确定是我编写测试的方式有问题还是应用程序本身有问题。下面是错误。
Previous render Next render
------------------------------------------------------
1. useState useState
2. undefined useEffect
我在失败的测试中看到了这条消息。"比上一次渲染时渲染了更多的钩子。 "
当我在 useEffect 上添加控制台语句时,我看到它只被调用了一次。
下面是我的 Auth 组件。
const Auth: React.FC<Props> = (props) => {
const state = useConsoleState();
const [problemType, setProblemType] = React.useState<ProblemTypeEnum>("TECH");
React.useEffect(() => {
switch (props.supportType) {
case "limit":
setProblemType("LIMIT");
break;
case "account":
setProblemType("ACCOUNT");
break;
default:
setProblemType("TECH");
break;
}
}, [props.supportType]);
};
const userId = getUserOcid(state.userProfile);
const cimsUserValidationResult = authApiCalls.callCims(!props.csi, props.csi, userId, problemType, state.homeRegionName);
和我的测试
describe("Auth tests", () => {
beforeEach(() => {
const useEffect = jest.spyOn(React, "useEffect");
useEffect.mockImplementationOnce(f => f());
authApiCalls.callCims = jest.fn().mockReturnValue({
loading: false,
response: {
response: {
ok: true,
},
},
} as QueryResult<ValidationResponse>);
});
const runProblemTypeTest = (url: string, supportType: SupportType) => {
window = Object.create(window);
Object.defineProperty(window, "location", {
value: {
href: url,
},
writable: true
});
mount(
<Auth supportType=. {supportType}>
<div>TestChild</div>
</Authorization>
);
expect(authApiCalls.callCims).toHaveBeenCalledWith(
false,
"1234",
"test",
supportType,
"homeRegion"
);
};
it("check problem type passed to validate when problem type absent in the url", () => {
runProblemTypeTest("http://www.test.com", "tech");
});
});
解决方案
推荐阅读
- excel - 如何使用 VBA 和 Match 函数更新 Excel 表格中的单元格值?
- powershell - 在PowerShell中传递空日期时间参数
- lua - Lua - 如何在一个打印语句中打印两件事
- apache-spark - 在 Databricks 中读取多个多行 JSON 文件时出现错误
- flutter - Flutter 崩溃报告
- sql - 如何将 RegEx 模式转换为 SQL SELECT 语句以进行字符串匹配
- tcl - 如何调试 C 和 R 之间使用的 tcl/tk 代码
- python - 在
' 需要字符串作为左操作数,而不是元组 - c++ - C++中的动态分配和大数据结构
- sql - 比较 2 个字符串并找出不匹配项