Ошибка чтения свойства из настраиваемого хука React во время тестов

Я пытаюсь создать собственный хук для 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 недоступна из настраиваемого хука?

1 ответ

Вам нужно убедиться, что вы возвращаете результат своего хука из 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
  }
}));
Другие вопросы по тегам