signoz/frontend/src/tests/test-utils.tsx

301 lines
6.7 KiB
TypeScript
Raw Normal View History

/* eslint-disable sonarjs/no-duplicate-string */
import { render, RenderOptions, RenderResult } from '@testing-library/react';
import { FeatureKeys } from 'constants/features';
import ROUTES from 'constants/routes';
import { ResourceProvider } from 'hooks/useResourceAttribute';
import { AppContext } from 'providers/App/App';
import { IAppContext } from 'providers/App/types';
import { QueryBuilderProvider } from 'providers/QueryBuilder';
Feat: Timezone picker feature (#6474) * feat: time picker hint and timezone picker UI with basic functionality + helper to get timezones * feat: add support for esc keypress to close the timezone picker * chore: add the selected timezone as url param and close timezone picker on select * fix: overall improvement + add searchIndex to timezone * feat: timezone preferences UI * chore: improve timezone utils * chore: change timezone item from div to button * feat: display timezone in timepicker input * chore: fix the typo * fix: don't focus on time picker when timezone is clicked * fix: fix the issue of timezone breaking for browser and utc timezones * fix: display the timezone in timepicker hint 'You are at' * feat: timezone basic functionality (#6492) * chore: change div to fragment + change type to any as the ESLint complains otherwise * chore: manage etc timezone filtering with an arg * chore: update timezone wrapper class name * fix: add timezone support to downloaded logs * feat: add current timezone to dashboard list and configure metadata modal * fix: add pencil icon next to timezone hint + change the copy to Current timezone * fix: properly handle the escape button behavior for timezone picker * chore: replace @vvo/tzdb with native Intl API for timezones * feat: lightmode for timezone picker and timezone adaptation components * fix: use normald tz in browser timezone * fix: timezone picker lightmode fixes * feat: display selected time range in 12 hour format * chore: remove unnecessary optional chaining * fix: fix the typo in css variable * chore: add em dash and change icon for timezone hint in date/time picker * chore: move pen line icon to the right of timezone offset * fix: fix the failing tests * feat: handle switching off the timezone adaptation
2024-12-16 10:27:20 +04:30
import TimezoneProvider from 'providers/Timezone';
import React, { ReactElement } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import store from 'store';
import {
LicenseEvent,
LicensePlatform,
LicenseState,
LicenseStatus,
} from 'types/api/licensesV3/getActive';
import { ROLES } from 'types/roles';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
},
},
});
beforeEach(() => {
jest.useFakeTimers();
jest.setSystemTime(new Date('2023-10-20'));
});
afterEach(() => {
queryClient.clear();
jest.useRealTimers();
});
const mockStore = configureStore([thunk]);
const mockStored = (role?: string): any =>
mockStore({
...store.getState(),
app: {
...store.getState().app,
role, // Use the role provided
user: {
userId: '6f532456-8cc0-4514-a93b-aed665c32b47',
email: 'test@signoz.io',
name: 'TestUser',
profilePictureURL: '',
accessJwt: '',
refreshJwt: '',
},
isLoggedIn: true,
org: [
{
createdAt: 0,
hasOptedUpdates: false,
id: 'xyz',
isAnonymous: false,
name: 'Test Inc. - India',
},
],
},
});
jest.mock('react-i18next', () => ({
useTranslation: (): {
t: (str: string) => string;
i18n: {
changeLanguage: () => Promise<void>;
};
} => ({
t: (str: string): string => str,
i18n: {
changeLanguage: (): Promise<void> => new Promise(() => {}),
},
}),
}));
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useLocation: (): { pathname: string } => ({
pathname: `${process.env.FRONTEND_API_ENDPOINT}/${ROUTES.TRACES_EXPLORER}/`,
}),
}));
Feat: back navigation support throughout the app (#6701) * feat: custom hook to prevent redundant navigation and handle default params with URL comparison * feat: implement useSafeNavigation to QB, to ensure that the back navigation works properly * fix: handle syncing the relativeTime param with the time picker selected relative time * feat: add support for absolute and relative time sync with time picker component * refactor: integrate safeNavigate in LogsExplorerChart and deprecate the existing back navigation * feat: update pagination query params on pressing next/prev page * fix: fix the issue of NOOP getting converted to Count on coming back from alert creation page * refactor: replace history navigation with safeNavigate in DateTimeSelectionV2 component it also fixes the issue of relativeTime not being added to the url on mounting * feat: integrate useSafeNavigate across service details tabs * fix: fix duplicate redirections by converting the timestamp to milliseconds * fix: replace history navigation with useSafeNavigate in LogsExplorerViews and useUrlQueryData * fix: replace history navigation with useSafeNavigate across dashboard components * fix: use safeNavigate in alert components * fix: fix the issue of back navigation in alert table and sync the pagination with url param * fix: handle back navigation for resource filter and sync the state with url query * fix: fix the issue of double redirection from top operations to traces * fix: replace history.push with safeNavigate in TracesExplorer's updateDashboard * fix: prevent unnecessary query re-runs by checking stagedQuery before redirecting in NewWidget * chore: cleanup * fix: fix the failing tests * fix: fix the documentation redirection failing tests * test: mock useSafeNavigate hook in WidgetGraphComponent test * test: mock useSafeNavigate hook in ExplorerCard test
2025-02-14 08:24:49 +04:30
jest.mock('hooks/useSafeNavigate', () => ({
useSafeNavigate: (): any => ({
safeNavigate: jest.fn(),
}),
}));
jest.mock('react-router-dom-v5-compat', () => ({
...jest.requireActual('react-router-dom-v5-compat'),
useNavigationType: (): any => 'PUSH',
}));
export function getAppContextMock(
role: string,
appContextOverrides?: Partial<IAppContext>,
): IAppContext {
return {
activeLicenseV3: {
event_queue: {
created_at: '0',
event: LicenseEvent.NO_EVENT,
scheduled_at: '0',
status: '',
updated_at: '0',
},
state: LicenseState.ACTIVE,
status: LicenseStatus.VALID,
platform: LicensePlatform.CLOUD,
created_at: '0',
plan: {
created_at: '0',
description: '',
is_active: true,
name: '',
updated_at: '0',
},
plan_id: '0',
free_until: '0',
updated_at: '0',
valid_from: 0,
valid_until: 0,
},
trialInfo: {
trialStart: -1,
trialEnd: -1,
onTrial: false,
workSpaceBlock: false,
trialConvertedToSubscription: false,
gracePeriodEnd: -1,
},
isFetchingActiveLicenseV3: false,
activeLicenseV3FetchError: null,
user: {
accessJwt: 'some-token',
refreshJwt: 'some-refresh-token',
id: 'some-user-id',
email: 'does-not-matter@signoz.io',
name: 'John Doe',
profilePictureURL: '',
createdAt: 1732544623,
organization: 'Nightswatch',
orgId: 'does-not-matter-id',
role: role as ROLES,
groupId: 'does-not-matter-groupId',
},
org: [
{
createdAt: 0,
hasOptedUpdates: false,
id: 'does-not-matter-id',
isAnonymous: false,
name: 'Pentagon',
},
],
isFetchingUser: false,
userFetchError: null,
licenses: {
licenses: [
{
key: 'does-not-matter',
isCurrent: true,
planKey: 'ENTERPRISE_PLAN',
ValidFrom: new Date(),
ValidUntil: new Date(),
status: 'VALID',
},
],
},
isFetchingLicenses: false,
licensesFetchError: null,
featureFlags: [
{
name: FeatureKeys.SSO,
active: true,
usage: 0,
usage_limit: -1,
route: '',
},
{
name: FeatureKeys.USE_SPAN_METRICS,
active: false,
usage: 0,
usage_limit: -1,
route: '',
},
{
name: FeatureKeys.GATEWAY,
active: true,
usage: 0,
usage_limit: -1,
route: '',
},
{
name: FeatureKeys.PREMIUM_SUPPORT,
active: true,
usage: 0,
usage_limit: -1,
route: '',
},
{
name: FeatureKeys.ANOMALY_DETECTION,
active: true,
usage: 0,
usage_limit: -1,
route: '',
},
{
name: FeatureKeys.ONBOARDING,
active: true,
usage: 0,
usage_limit: -1,
route: '',
},
{
name: FeatureKeys.CHAT_SUPPORT,
active: true,
usage: 0,
usage_limit: -1,
route: '',
},
],
isFetchingFeatureFlags: false,
featureFlagsFetchError: null,
orgPreferences: [
{
key: 'ORG_ONBOARDING',
name: 'Organisation Onboarding',
description: 'Organisation Onboarding',
valueType: 'boolean',
defaultValue: false,
allowedValues: [true, false],
isDiscreteValues: true,
allowedScopes: ['org'],
value: false,
},
],
isFetchingOrgPreferences: false,
orgPreferencesFetchError: null,
isLoggedIn: true,
updateUser: jest.fn(),
updateOrg: jest.fn(),
updateOrgPreferences: jest.fn(),
licensesRefetch: jest.fn(),
...appContextOverrides,
};
}
function AllTheProviders({
children,
role, // Accept the role as a prop
appContextOverrides,
}: {
children: React.ReactNode;
role: string; // Define the role prop
appContextOverrides: Partial<IAppContext>;
}): ReactElement {
return (
<QueryClientProvider client={queryClient}>
<ResourceProvider>
<Provider store={mockStored(role)}>
<AppContext.Provider value={getAppContextMock(role, appContextOverrides)}>
<BrowserRouter>
{/* Use the mock store with the provided role */}
<TimezoneProvider>
<QueryBuilderProvider>{children}</QueryBuilderProvider>
</TimezoneProvider>
</BrowserRouter>
</AppContext.Provider>
</Provider>
</ResourceProvider>
</QueryClientProvider>
);
}
const customRender = (
ui: ReactElement,
options?: Omit<RenderOptions, 'wrapper'>,
role = 'ADMIN', // Set a default role
appContextOverrides?: Partial<IAppContext>,
): RenderResult =>
render(ui, {
wrapper: () => (
<AllTheProviders role={role} appContextOverrides={appContextOverrides || {}}>
{ui}
</AllTheProviders>
),
...options,
});
export * from '@testing-library/react';
export { customRender as render };