使用react-hooks-testing-library测试自定义钩子会引发错误

时间:2019-05-10 22:16:58

标签: jestjs react-hooks-testing-library

我正在尝试测试一个简单的钩子,该钩子使用axios来获取一些数据。但是,测试将引发TypeError:“无法读取未定义的属性'fetchCompanies'。这是我的自定义钩子(the full repo is here):

import { useState, useEffect } from 'react';
import { Company } from '../../models';
import { CompanyService } from '../../services';

export const useCompanyList = (): {
    loading: boolean;
    error: any;
    companies: Array<Company>;
} => {
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState();
    const [companies, setCompanies] = useState<Array<Company>>([]);

    useEffect(() => {
        const fetchData = async () => {
            try {
                setLoading(true);
                const companies = await CompanyService.fetchCompanies();

                // Sort by ticker
                companies.sort((a, b) => {
                    if (a.ticker < b.ticker) return -1;
                    if (a.ticker > b.ticker) return 1;
                    return 0;
                });
                setCompanies(companies);
                setLoading(false);
            } catch (e) {
                setError(e);
            }
        };

        fetchData();
    }, []);

    return { loading, error, companies };
};

这是我的测试:

import { renderHook } from 'react-hooks-testing-library';
import { useCompanyList } from './useCompanyList';

const companiesSorted = [
    {
        ticker: 'AAPL',
        name: 'Apple Inc.'
    },
    ...
];

jest.mock('../../services/CompanyService', () => {
    const companiesUnsorted = [
        {
            ticker: 'MSFT',
            name: 'Microsoft Corporation'
        },
        ...
    ];

    return {
        fetchCompanies: () => companiesUnsorted
    };
});

describe('useCompanyList', () => {
    it('returns a sorted list of companies', () => {
        const { result } = renderHook(() => useCompanyList());

        expect(result.current.loading).toBe(true);
        expect(result.current.error).toBeUndefined();
        expect(result.current.companies).toEqual(companiesSorted);
    });
});

请帮助我了解在这种情况下如何使用react-hooks-testing-library。

修改

这似乎与似乎已解决的Jest问题有关。请参阅https://github.com/facebook/jest/pull/3209

1 个答案:

答案 0 :(得分:1)

The

  

TypeError:“无法读取未定义的属性'fetchCompanies'”

是由您定义CompanyService服务的方式引起的。在代码中,您将使用所有服务方法导出对象CompanyService。但是在测试中,您正在模拟CompanyService以使用方法返回对象。

因此,该模拟应返回一个CompanyService对象,该对象是具有所有方法的对象:

jest.mock('../../services/CompanyService', () => {
    const companiesUnsorted = [
        {
            ticker: 'MSFT',
            name: 'Microsoft Corporation'
        },
        ...
    ];

    return {
        CompanyService: {
            fetchCompanies: () => companiesUnsorted
        }
    };
});

现在,一旦解决此问题,您将发现您不再拥有TypeError,但是您的测试未通过。这是因为您要测试的代码是异步的,但您的测试不是异步的。因此,在渲染钩子之后(通过renderHookresult.current.companies将立即为空数组。

您将不得不等待您的诺言解决。幸运的是,react-hooks-testing-library为我们提供了waitForNextUpdate函数,以等待下一次挂钩更新。因此,测试的最终代码如下:

it('returns a sorted list of companies', async () => {
    const { result, waitForNextUpdate } = renderHook(() => useCompanyList());

    expect(result.current.loading).toBe(true);
    expect(result.current.error).toBeUndefined();
    expect(result.current.companies).toEqual([]);

    await waitForNextUpdate();

    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
    expect(result.current.companies).toEqual(companiesSorted);
});