Reputation: 917
I'm trying to create a custom hook for React so I can isolate and test the view logic. Here's a simplified version of my hook:
import {useState} from "react";
function useQuestionInput() {
const [category, set_category] = useState("");
return {set_category, category}
}
export {useQuestionInput}
My test looks like this:
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");
})
});
When my tests execute I get an error because the set_category property is not present:
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)
Why is the set_category function not accessible from the custom hook?
Upvotes: 3
Views: 1014
Reputation: 6944
You need to ensure you are returning the result of your hook from the renderHook
callback.
const {result} = renderHook(() => {
// no return
useQuestionInput({
onQuestionCreation: (created_question) => {
question = created_question
}
})
});
Change this to
const {result} = renderHook(() => {
return useQuestionInput({
onQuestionCreation: (created_question) => {
question = created_question
}
})
});
or just
const {result} = renderHook(() => useQuestionInput({
onQuestionCreation: (created_question) => {
question = created_question
}
}));
Upvotes: 1