我试图在我的测试中模拟获取状态。成功模拟了有数据的状态和有错误的状态。您可以在下面找到一个示例:
const createMenuWithGraphQL = (graphqlData: MockGraphQLResponse): [JSX.Element, MockGraphQLClient] => {
const mockGraphQLClient = {
executeQuery: jest.fn(() => fromValue(graphqlData)),
executeMutation: jest.fn(() => never),
executeSubscription: jest.fn(() => never),
};
return [
<GraphQLProvider key="provider" value={mockGraphQLClient}>
<Menu {...menuConfig} />
</GraphQLProvider>,
mockGraphQLClient,
];
};
it('displays submenu with section in loading state after clicking on an item with children', async () => {
const [Component, client] = createMenuWithGraphQL({
fetching: true,
error: false,
});
const { container } = render(Component);
const itemConfig = menuConfig.links[0];
fireEvent.click(screen.getByText(label));
await waitFor(() => {
const alertItem = screen.getByRole('alert');
expect(client.executeQuery).toBeCalledTimes(1);
expect(container).toContainElement(alertItem);
expect(alertItem).toHaveAttribute('aria-busy', 'false');
});
});
该组件如下所示:
export const Component: FC<Props> = ({ label, identifier }) => {
const [result] = useQuery({ query });
return (
<div role="group">
{result.fetching && (
<p role="alert" aria-busy={true}>
Loading
</p>
)}
{result.error && (
<p role="alert" aria-busy={false}>
Error
</p>
)}
{!result.fetching && !result.error && <p>Has data</p>}
</div>
);
};
我不知道我做错了什么。当我运行测试时,它说fetching
is false
。任何帮助,将不胜感激。