reactjs - 使用 Jest 和 react 测试库进行单元测试自定义 Hook

标签 reactjs unit-testing jestjs react-testing-library

我正在尝试使用 jest 和 React 测试库对自定义钩子(Hook)进行单元测试,在抛出错误的情况下,但我无法捕获实际的错误消息,这是迄今为止我的代码:

我的第一个钩子(Hook):

import react from 'react';

const useFirstHook = () => {

    //I will add conditional logic later
    throw new Error('my custom error is thrown')

    const test1 = 'I am test 1';

    return {
        test1
    };

};

export default useFirstHook;

测试.js

import React from 'react';
import { render } from '@testing-library/react';

import useFirstHook from './useFirstHook';

describe('useFirstHook', () => {

    //I also tried adding jest.spy but no luck
    /* beforeAll(() => {
        jest.spyOn(console, 'error').mockImplementation(() => {})
    }); */

    it('test 1', () => {

        let result;

        const TestComponent = () => {
            result = useFirstHook()
            return null;
        };

        render(<TestComponent />)

        //expect()

    });

});

我的逻辑是首先创建一个钩子(Hook),对其进行单元测试,然后创建组件,在其中添加钩子(Hook)并使用钩子(Hook)集成测试该组件。我错过了什么,或者我的方法完全错误?

最佳答案

一个好的方法是测试已经包含钩子(Hook)的组件本身。

如果您认为需要在没有组件的情况下测试钩子(Hook),您可以使用@testing-library/react-hooks包,例如:

const useFirstHook = (shouldThrow = false) => {
  // throw onmount
  useEffect(() => {
    if (shouldThrow) throw new Error('my custom error is thrown');
  }, [shouldThrow]);

  return {
    test1: 'I am test 1'
  };
};

describe('useFirstHook', () => {
  it('should not throw', () => {
    const { result } = renderHook(() => useFirstHook(false));
    expect(result.current.test1).toEqual('I am test 1');
  });

  it('should throw', () => {
    try {
      const { result } = renderHook(() => useFirstHook(true));
      expect(result.current).toBe(undefined);
    } catch (err) {
      expect(err).toEqual(Error('my custom error is thrown'));
    }
  });
});

关于reactjs - 使用 Jest 和 react 测试库进行单元测试自定义 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66545990/

相关文章:

typescript - 使用 TypeScript 和 JestJS 测试无效的函数参数

typescript - Jest spyOn 不适用于 typescript : "Property ' mockRestore' is missing in type 'Spy' "

javascript - React Native 在 React Native Web 中将 this.state.input 存储为 Undefined Work 被罚款

ruby-on-rails - 如何将 Rails 助手导入到功能测试中

java - 如何在junit测试中比较两个bytearrayinputstream?

unit-testing - 如何在 golang 中模拟 Zookeeper 服务器进行单元测试?

javascript - 如何设置 Jest 来测试 Canvas

node.js - 如何正确地将更改推送到 Heroku

reactjs - 如何在 react 大日历中获取月 View 中周的全日名称

javascript - 如何循环遍历 on React 列表?