首页 > 解决方案 > 在测试期间从 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 函数?

标签: reactjsreact-hooksreact-hooks-testing-library

解决方案


您需要确保从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
  }
}));

推荐阅读