我正在尝试为React创建一个自定义挂钩,以便隔离和测试视图逻辑。这是我的钩子的简化版本:
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)
为什么不能从自定义挂钩访问set_category函数?
您需要确保从renderHook
回调返回钩子的结果。
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
}
}));