Use jest.fakeTimers instead of mocking Date.now (#48121)

This commit is contained in:
Ashley Harrison 2022-04-22 16:00:37 +01:00 committed by GitHub
parent e9ad2207be
commit 277a83215c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,12 +1,17 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { UserEvent } from '@testing-library/user-event/dist/types/setup';
import React from 'react';
import * as runtime from '@grafana/runtime';
import { customBuilder } from '../shared/testing/builders';
import { VariablesUnknownTable, VariablesUnknownTableProps } from './VariablesUnknownTable';
import {
SLOW_VARIABLES_EXPANSION_THRESHOLD,
VariablesUnknownTable,
VariablesUnknownTableProps,
} from './VariablesUnknownTable';
import * as utils from './utils';
import { UsagesToNetwork } from './utils';
@ -100,25 +105,40 @@ describe('VariablesUnknownTable', () => {
});
describe('but when the unknown processing takes a while', () => {
const origDateNow = Date.now;
let user: UserEvent;
beforeEach(() => {
jest.useFakeTimers();
// Need to use delay: null here to work with fakeTimers
// see https://github.com/testing-library/user-event/issues/833
user = userEvent.setup({ delay: null });
});
afterEach(() => {
Date.now = origDateNow;
jest.useRealTimers();
});
it('then it should report slow expansion', async () => {
const variable = customBuilder().withId('Renamed Variable').withName('Renamed Variable').build();
const usages = [{ variable, nodes: [], edges: [], showGraph: false }];
const { reportInteractionSpy } = await getTestContext({}, usages);
const dateNowStart = 1000;
const dateNowStop = 2000;
Date.now = jest.fn().mockReturnValueOnce(dateNowStart).mockReturnValue(dateNowStop);
const { getUnknownsNetworkSpy, reportInteractionSpy } = await getTestContext({}, usages);
getUnknownsNetworkSpy.mockImplementation(() => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(usages);
}, SLOW_VARIABLES_EXPANSION_THRESHOLD);
});
});
await userEvent.click(screen.getByRole('heading', { name: /renamed or missing variables/i }));
await user.click(screen.getByRole('heading', { name: /renamed or missing variables/i }));
jest.advanceTimersByTime(SLOW_VARIABLES_EXPANSION_THRESHOLD);
// make sure we report the interaction for slow expansion
await waitFor(() =>
expect(reportInteractionSpy).toHaveBeenCalledWith('Slow unknown variables expansion', { elapsed: 1000 })
expect(reportInteractionSpy).toHaveBeenCalledWith('Slow unknown variables expansion', {
elapsed: expect.any(Number),
})
);
});
});