我正在尝试测试一个使用axios获取一些数据的简单钩子。然而,该测试正在抛出一个TypeError:“无法读取未定义的属性'fetchCompanies‘”。下面是我的自定义钩子(完整的回购在这里):
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);
});
});请帮助我理解如何使用反应钩-测试-库在这种情况下。
编辑
这似乎与一个看似已经解决的Jest问题有关。请看https://github.com/facebook/jest/pull/3209。
发布于 2019-05-13 13:14:49
这个
TypeError:“无法读取未定义的属性'fetchCompanies‘”
是由定义CompanyService服务的方式造成的。在代码中,您要导出一个带有所有服务方法的对象CompanyService。但是在您的测试中,您是在模拟CompanyService以返回一个带有方法的对象。
因此,模拟应该返回一个CompanyService对象,它是一个具有所有方法的对象:
jest.mock('../../services/CompanyService', () => {
const companiesUnsorted = [
{
ticker: 'MSFT',
name: 'Microsoft Corporation'
},
...
];
return {
CompanyService: {
fetchCompanies: () => companiesUnsorted
}
};
});现在,一旦您解决了这个问题,您将发现您已经没有TypeError了,但是您的测试没有通过。这是因为您要测试的代码是异步的,但是您的测试不是异步的。因此,在您呈现钩子(通过renderHook)之后,result.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);
});https://stackoverflow.com/questions/56085458
复制相似问题