问题描述
我找不到任何关于如何在 useEffect
中测试多个同步提取请求的文章或文档。我正在获取数据,然后在第二次获取开始之前,我在按钮上设置了“加载数据”工具提示。一旦第二次获取完成,工具提示要么变成“无法使用此功能”,要么根本没有工具提示。我不知道如何进入测试的那些状态,其中 jest 在 fetch 调用之前或之后。
问题是我的测试没有看到开始时的“加载数据”工具提示,即使它在我手动测试时出现。我很难理解何时等待第二次呼叫,何时实际发生以及何时完成...
只是为了澄清 getAccountInfo
是一个获取请求函数,它返回一个具有 accountInfo
属性的对象。
错误:
TestingLibraryElementError: Unable to find an element with the text: /loading data/。这可能是因为文本被多个元素分解了。在这种情况下,您可以为您的文本匹配器提供一个函数,使您的匹配器更加灵活。
这是我的测试
import React from 'react';
import * as utils from '../utils';
import { render,screen,fireEvent,waitFor } from '@testing-library/react';
import fetch from 'jest-fetch-mock';
const getAccountInfoSpy = jest.spyOn(utils,'getAccountInfo');
const testId = 'ABCDEF';
describe('AccountInfo',() => {
beforeAll(() => fetch.enableMocks());
afterall(() => fetch.disableMocks());
beforeEach(() => jest.clearallMocks());
it('displays "loading data" tooltip on hover' () => {
fetch.mockResponse(
JSON.stringify({
orgId: testId,name: 'Adam',}),{ status: 200 },);
const { getByRole,findByText } = render(
<AccountInfo />
);
const importButton = getByRole('button',{ name: 'Import' });
fireEvent.mouseEnter(importButton);
expect(await findByText(/loading data/)).toBeInTheDocument();
await waitFor(() =>
expect(getAccountInfoSpy).toHaveBeenCalledWith(testId),);
expect(findByText(/cannot use this feature/).toBeInTheDocument();
});
});
这是 AccountInfo 组件
const AccountInfo = () => {
const { customerId } = useCustomerContext();
const [isLoading,setIsLoading] = useState(true);
const [accountInfo,setAccountInfo] = useState({});
const [isAccountInfoLoading,setIsAccountInfoLoading] = useState(false);
useEffect(() => {
const fetchAccountData = async () => {
const rawRes = await fetch(`/customer/${customerId}`);
const res = await rawRes.json();
setIsLoading(false);
if (res.orgId) {
setIsAccountInfoLoading(true);
try {
const accountInfoRes = await getAccountInfo(res.orgId);
setAccountInfo(accountInfoRes.accountInfo);
} catch (error) {
console.log('error',error);
} finally {
setIsAccountInfoLoading(false);
}
}
}
fetchAccountData();
});
function renderTooltip() {
if (isAccountInfoLoading) {
return 'loading data';
} else {
return !accountInfo.active
? 'cannot use this feature'
: undefined;
}
}
return (
<>
<Button tooltip={renderTooltip()}>
Import
</Button>
</>
);
};
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)