【问题标题】:unit test custom hook with jest and react testing library使用 jest 和 react 测试库对自定义钩子进行单元测试
【发布时间】:2021-06-07 06:55:57
【问题描述】:

我正在尝试使用 jest 对自定义钩子进行单元测试,并在引发错误但我无法捕获实际错误消息的情况下对测试库做出反应,这是我目前的代码:

我的第一个钩子:

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;

test.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()

    });

});

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

【问题讨论】:

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


【解决方案1】:

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

如果您认为钩子需要在没有组件的情况下进行测试,您可以使用@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'));
    }
  });
});

【讨论】:

    猜你喜欢
    • 2021-12-26
    • 2022-01-13
    • 2021-04-17
    • 2022-06-15
    • 1970-01-01
    • 2021-12-27
    • 2021-03-10
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多