2

我正在尝试为 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 函数?

4

1 回答 1

0

您需要确保从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
  }
}));
于 2020-03-24T22:30:10.903 回答