gpt4 book ai didi

reactjs - 测试期间从 React 自定义 Hook 读取属性时出错

转载 作者:行者123 更新时间:2023-12-05 06:19:32 25 4
gpt4 key购买 nike

我正在尝试为 React 创建一个自定义 Hook ,以便我可以隔离和测试 View 逻辑。这是我的钩子(Hook)的简化版本:

import {useState} from "react";

function useQuestionInput() {
const [category, set_category] = useState("");

return {set_category, category}
}

export {useQuestionInput}

我的测试是这样的:

describe("Question Input View Model", function () {
it("intial values are empty", function () {
const {result} = renderHook(() => useQuestionInput({}));

expect(result.current.category).to.equal("");
});

it("addQuestion calls props", function () {
let question = null;

const {result} = renderHook(() => {
useQuestionInput({
onQuestionCreation: (created_question) => {
question = created_question
}
})
});

act(() => {
result.current.set_category("new Category")
})

expect(result.current.category).to.equal("new Category");
})
});

当我执行测试时出现错误,因为 set_category 属性不存在:

1) Question Input View Model
addQuestion calls props:
TypeError: Cannot read property 'set_category' of undefined
at /Users/jpellat/workspace/Urna/urna_django/website/tests/components.test.js:27:28
at batchedUpdates (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12395:12)
at act (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14936:14)
at Context.<anonymous> (tests/components.test.js:26:9)
at processImmediate (internal/timers.js:456:21)

为什么无法从自定义 Hook 访问 set_category 函数?

最佳答案

您需要确保从 renderHook 回调中返回钩子(Hook)的结果。

const {result} = renderHook(() => {
// no return
useQuestionInput({
onQuestionCreation: (created_question) => {
question = created_question
}
})
});

将此更改为

const {result} = renderHook(() => {
return useQuestionInput({
onQuestionCreation: (created_question) => {
question = created_question
}
})
});

或者只是

const {result} = renderHook(() => useQuestionInput({
onQuestionCreation: (created_question) => {
question = created_question
}
}));

关于reactjs - 测试期间从 React 自定义 Hook 读取属性时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60805171/

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