Jest.js 如何测试返回React函数的React钩子

pcrecxhr  于 2023-11-15  发布在  Jest
关注(0)|答案(1)|浏览(161)

我需要测试下面给出的钩子,但找不到类似的例子或课程来测试下面的钩子:

export const useListAllThreads = () => {
    const {miraklListAllThreads} = useM11()
    const {getTokenWhenReady} = useAccessToken()

    return {
        /**
         * List all threads - Mirakl m11
         * @param {string} customerID - Customer id to include in result
         * @returns {Object} result - The result object with data, success, and msg
         */
        async getMiraklListAllThreads(customerID) {
            const token = await getTokenWhenReady()
            let result = {
                data: null,
                success: false,
                msg: null
            }

            try {
                const params = {
                    customer_id: customerID
                }

                const response = await miraklListAllThreads(params, token)
                if (!response || response.success == false) {
                    result.msg = 'Error getting Mirakl M11. Please check your configuration.'
                    result.success = false
                } else {
                    result.data = response.data
                    result.success = true
                }
            } catch (error) {
                result.msg = error.message
                result.success = false
            }

            return result
        }
    }
}

字符串
有人能帮我为这个钩子创建一个单元测试吗?
我试着模仿miraklListAllThreadsgetTokenWhenReady,然后尝试钩子的功能,但无法实现。

bxfogqkk

bxfogqkk1#

您可以使用react-testing-library中的renderHook方法。

import { renderHook } from '@testing-library/react-hooks';
import { useListAllThreads } from './path-to-your-hook';
import { useM11 } from './path-to-your-useM11-hook';
import { useAccessToken } from './path-to-your-useAccessToken-hook';

// Mock the other hooks
jest.mock('./path-to-your-useM11-hook');
jest.mock('./path-to-your-useAccessToken-hook');

describe('useListAllThreads', () => {
  it('should call miraklListAllThreads with the correct parameters and return the result', async () => {
    // Mock the functions inside the dependencies
    const mockMiraklListAllThreads = jest.fn();
    const mockGetTokenWhenReady = jest.fn();

    // Mock the data you expect to receive from miraklListAllThreads
    const mockMiraklResponse = {
      success: true,
      data: 'mockData',
    };

    // Set up the mock implementation for your dependencies
    useM11.mockReturnValue({ miraklListAllThreads: mockMiraklListAllThreads });
    useAccessToken.mockReturnValue({ getTokenWhenReady: mockGetTokenWhenReady });

    // Set up the mock implementation for getTokenWhenReady
    mockGetTokenWhenReady.mockResolvedValue('mockToken');

    // Set up the mock implementation for miraklListAllThreads
    mockMiraklListAllThreads.mockResolvedValue(mockMiraklResponse);

    // Render the hook
    const { result, waitForNextUpdate } = renderHook(() => useListAllThreads());

    // Call the hook function
    const customerID = '123';
    const promise = result.current.getMiraklListAllThreads(customerID);

    // Ensure that miraklListAllThreads is called with the correct parameters
    await waitForNextUpdate();
    expect(mockMiraklListAllThreads).toHaveBeenCalledWith({ customer_id: customerID }, 'mockToken');

    // Ensure that the hook returns the expected result
    const expectedResult = {
      data: 'mockData',
      success: true,
      msg: null,
    };
    await expect(promise).resolves.toEqual(expectedResult);
  });
});

字符串

相关问题