这是组件
const Analytics = () => {
const [isLoading,setIsLoading]=useState(true);
const handleAnnouncementsClick = () => {
navigate('/applications/announcements');
};
return (
<DashboardLayout>
<DashboardNavbar />
{isLoading ? (
showLoader()
) : (
<>
<Grid container spacing={3}>
<DashboardLeftGrid item xs={12} sm={6}>
<AnnouncementCard
ispermission={handleBooleanProp(true)}
onClick={handleAnnouncementsClick}
data-testid="Announcements"
>
<HeadingMuiTypography variant="h6">
Announcements
</HeadingMuiTypography>
<DashboardAnnouncements />
</AnnouncementCard>
</DashboardLeftGrid>
)
}
这是单元测试用例组件 如果 isLoading 状态变为 false 那么只有测试用例通过,否则失败
如果我评论 isLoading 相关条件测试用例变为通过,请尝试帮助我
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import Analytics from './index';
import { testComponent } from 'utils/commonUtils';
describe('Analytics component', () => {
test('renders Analytics component correctly', async () => {
render(testComponent(<Analytics />));
expect(screen.getByTestId(/Announcements/i)).toBeInTheDocument();
});
});
您将要测试加载程序是否显示,然后触发将 isLoading 设置为 false 的任何内容,然后测试公告是否可见。并且您使测试异步,因此我假设涉及一些异步逻辑,因此您应该使用 waitFor (或 find)等待它
test('renders Analytics when loading is done, loader otherwise', async () => {
render(testComponent(<Analytics />));
await waitFor(() => {
expect(screen.getByTestId(LoadingComponent).toBeVisible();
})
await user.press(screen.getTheButtonThatTriggersTheLoadingToBeDone())
await waitFor(() => {
expect(screen.getByTestId(AnnouncementComponent).toBeVisible();
})
});
我认为这应该是你的起点