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

284 lines
6.3 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 {
feat(license): build license service (#7969) * feat(license): base setup for license service * feat(license): delete old manager and import to new * feat(license): deal with features * feat(license): complete the license service in ee * feat(license): add sqlmigration for licenses * feat(license): remove feature flags * feat(license): refactor into provider pattern * feat(license): remove the ff lookup interface * feat(license): add logging to the validator functions * feat(license): implement features for OSS build * feat(license): fix the OSS build * feat(license): lets blast frontend * feat(license): fix the EE OSS build without license * feat(license): remove the hardcoded testing configs * feat(license): upgrade migration to 34 * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): integration tests * feat(license): integration tests * feat(license): refactor frontend * feat(license): make frontend api structure changes * feat(license): fix integration tests * feat(license): revert hardcoded configs * feat(license): fix integration tests * feat(license): address review comments * feat(license): address review comments * feat(license): address review comments * feat(license): address review comments * feat(license): update migration * feat(license): update migration * feat(license): update migration * feat(license): fixed logging * feat(license): use the unmarshaller for postable subscription * feat(license): correct the error message * feat(license): fix license test * feat(license): fix lint issues * feat(user): do not kill the service if upstream is down
2025-05-24 19:14:29 +05:30
activeLicense: {
key: 'test-key',
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,
},
feat(license): build license service (#7969) * feat(license): base setup for license service * feat(license): delete old manager and import to new * feat(license): deal with features * feat(license): complete the license service in ee * feat(license): add sqlmigration for licenses * feat(license): remove feature flags * feat(license): refactor into provider pattern * feat(license): remove the ff lookup interface * feat(license): add logging to the validator functions * feat(license): implement features for OSS build * feat(license): fix the OSS build * feat(license): lets blast frontend * feat(license): fix the EE OSS build without license * feat(license): remove the hardcoded testing configs * feat(license): upgrade migration to 34 * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): integration tests * feat(license): integration tests * feat(license): refactor frontend * feat(license): make frontend api structure changes * feat(license): fix integration tests * feat(license): revert hardcoded configs * feat(license): fix integration tests * feat(license): address review comments * feat(license): address review comments * feat(license): address review comments * feat(license): address review comments * feat(license): update migration * feat(license): update migration * feat(license): update migration * feat(license): fixed logging * feat(license): use the unmarshaller for postable subscription * feat(license): correct the error message * feat(license): fix license test * feat(license): fix lint issues * feat(user): do not kill the service if upstream is down
2025-05-24 19:14:29 +05:30
isFetchingActiveLicense: false,
activeLicenseFetchError: null,
user: {
accessJwt: 'some-token',
refreshJwt: 'some-refresh-token',
id: 'some-user-id',
email: 'does-not-matter@signoz.io',
chore(auth): refactor the client handlers in preparation for multi tenant login (#7902) * chore: update auth * chore: password changes * chore: make changes in oss code * chore: login * chore: get to a running state * fix: migration inital commit * fix: signoz cloud intgtn tests * fix: minor fixes * chore: sso code fixed with org domain * fix: tests * fix: ee auth api's * fix: changes in name * fix: return user in login api * fix: address comments * fix: validate password * fix: handle get domain by email properly * fix: move authomain to usermodule * fix: use displayname instead of hname * fix: rename back endpoints * fix: update telemetry * fix: correct errors * fix: test and fix the invite endpoints * fix: delete all things related to user in store * fix: address issues * fix: ee delete invite * fix: rename func * fix: update user and update role * fix: update role * chore(api): update the api folder structure according to rest principles * fix: login and invite changes * chore(api): update the api folder structure according to rest principles * chore(login): update the frontend according to the new APIs * fix: return org name in users response * chore(login): update the frontend according to the new APIs * fix: update user role * fix: nil check * chore(login): update the frontend according to the new API * fix: getinvite and update role * fix: sso * fix: getinvite use sso ctx * fix: use correct sourceurl * fix: getsourceurl from req payload * chore(login): update the frontend according to the new API * fix: update created_at * fix: fix reset password * chore(login): fixed reset password and bulk invites * fix: sso signup and token password change * fix: don't delete last admin * fix: reset password and migration * fix: migration * chore(login): fix the unwanted throw statement and tsconfig * fix: reset password for sso users * fix: clean up invite * chore(login): delete last admin user and reset password * fix: migration * fix: update claims and store code * fix: use correct error * fix: proper nil checks * fix: make migration multitenant * fix: address comments * fix: minor fixes * fix: test * fix: rename reset password * fix: set self restration only when sso endabled * chore(auth): update the invite user API * fix: integration tests * fix: integration tests * fix: integration tests * fix: integration tests * fix: integration tests * fix: integration tests * fix: integration tests * chore(auth): update integration test * fix: telemetry --------- Co-authored-by: nityanandagohain <nityanandagohain@gmail.com>
2025-05-14 23:53:41 +05:30
displayName: 'John Doe',
createdAt: 1732544623,
organization: 'Nightswatch',
orgId: 'does-not-matter-id',
role: role as ROLES,
},
org: [
{
createdAt: 0,
id: 'does-not-matter-id',
feat(organization): schema changes for the organizations entity (#7684) * feat(organization): add hname and alias for organization * fix: boolean values are not shown in the list panel's column * fix: moved logic to component level * fix: added type * fix: added test cases * fix: added test cases * chore: update copy webpack plugin * Revert "fix: display same key with multiple data types in filter suggestions by enhancing the deduping logic (#7255)" This reverts commit 1e85981a17a8e715e948308d3e85072d976907d3. * fix: use query search v2 for traces data source to handle multiple data types for the same key * fix(QueryBuilderSearchV2): add user typed option if it doesn't exist in the payload * fix(QueryBuilderSearchV2): increase the height of search dropdown for non-logs data sources * fix: display span scope selector for trace data source * chore: remove the span scope selector from qb search v1 and move the component to search v2 * fix: write test to ensure that we display span scope selector for traces data source * fix: limit converting -> only to log data source * fix: don't display empty suggestion if only spaces are typed * chore: tests for span scope selector * chore: qb search flow (key, operator, value) test cases * refactor: fix the Maximum update depth reached issue while running tests * chore: overall improvements to span scope selector tests Resource attr filter: style fix and quick filter changes (#7691) * chore: resource attr filter init * chore: resource attr filter api integration * chore: operator config updated * chore: fliter show hide logic and styles * chore: add support for custom operator list to qb * chore: minor refactor * chore: minor code refactor * test: quick filters test suite added * test: quick filters test suite added * test: all errors test suite added * chore: style fix * test: all errors mock fix * chore: test case fix and mixpanel update * chore: color update * chore: minor refactor * chore: style fix * chore: set default query in exceptions tab * chore: style fix * chore: minor refactor * chore: minor refactor * chore: minor refactor * chore: test update * chore: fix filter header with no query name * fix: scroll fix * chore: add data source traces to quick filters * chore: replace div with fragment --------- Co-authored-by: Aditya Singh <adityasingh@Adityas-MacBook-Pro.local> fix: handle rate operators for table panel (#7695) * fix: handle rate operators for table panel chore: fix error rate (#7701) Signed-off-by: Shivanshu Raj Shrivastava <shivanshu1333@gmail.com> * feat(organization): minor cleanups * feat(organization): better naming for api and usecase * feat(organization): better packaging for modules * feat(organization): change hname to displayName * feat(organization): update the migration to use dialect * feat(organization): update the migration to use dialect * feat(organization): update the migration to use dialect * feat(organization): revert back to impl * feat(organization): remove DI from organization * feat(organization): address review comments * feat(organization): address review comments * feat(organization): address review comments --------- Signed-off-by: Shivanshu Raj Shrivastava <shivanshu1333@gmail.com>
2025-04-25 19:38:15 +05:30
displayName: 'Pentagon',
},
],
isFetchingUser: false,
userFetchError: 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(),
feat(license): build license service (#7969) * feat(license): base setup for license service * feat(license): delete old manager and import to new * feat(license): deal with features * feat(license): complete the license service in ee * feat(license): add sqlmigration for licenses * feat(license): remove feature flags * feat(license): refactor into provider pattern * feat(license): remove the ff lookup interface * feat(license): add logging to the validator functions * feat(license): implement features for OSS build * feat(license): fix the OSS build * feat(license): lets blast frontend * feat(license): fix the EE OSS build without license * feat(license): remove the hardcoded testing configs * feat(license): upgrade migration to 34 * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): better naming and structure * feat(license): integration tests * feat(license): integration tests * feat(license): refactor frontend * feat(license): make frontend api structure changes * feat(license): fix integration tests * feat(license): revert hardcoded configs * feat(license): fix integration tests * feat(license): address review comments * feat(license): address review comments * feat(license): address review comments * feat(license): address review comments * feat(license): update migration * feat(license): update migration * feat(license): update migration * feat(license): fixed logging * feat(license): use the unmarshaller for postable subscription * feat(license): correct the error message * feat(license): fix license test * feat(license): fix lint issues * feat(user): do not kill the service if upstream is down
2025-05-24 19:14:29 +05:30
activeLicenseRefetch: 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 };