【问题标题】:Error reading property from React custom hook during tests在测试期间从 React 自定义钩子读取属性时出错
【发布时间】:2020-03-22 21:28:15
【问题描述】:

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

【问题讨论】:

    标签: reactjs react-hooks react-hooks-testing-library


    【解决方案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
      }
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 2021-04-25
      • 2021-04-17
      • 1970-01-01
      • 2023-03-13
      • 2020-04-13
      • 2020-07-10
      相关资源
      最近更新 更多