Chore: Some test type fixes (#81812)

some test type fixes
This commit is contained in:
Ashley Harrison
2024-02-05 09:47:30 +00:00
committed by GitHub
parent e50916ae64
commit dcf58555e8
28 changed files with 208 additions and 262 deletions

View File

@@ -1,6 +1,6 @@
import { map, of } from 'rxjs';
import { DataQueryRequest, DataSourceApi, LoadingState, PanelData } from '@grafana/data';
import { DataQueryRequest, DataSourceApi, DataSourceInstanceSettings, LoadingState, PanelData } from '@grafana/data';
import { locationService } from '@grafana/runtime';
import { SceneDataTransformer, SceneQueryRunner, VizPanel } from '@grafana/scenes';
import { DataQuery, DataSourceJsonData, DataSourceRef } from '@grafana/schema';
@@ -244,7 +244,7 @@ describe('VizPanelManager', () => {
await Promise.resolve();
await vizPanelManager.changePanelDataSource(
{ type: 'grafana-prometheus-datasource', uid: 'gdev-prometheus' } as any,
{ type: 'grafana-prometheus-datasource', uid: 'gdev-prometheus' } as DataSourceInstanceSettings,
[]
);
@@ -439,7 +439,7 @@ describe('VizPanelManager', () => {
module: 'prometheus',
id: 'grafana-prometheus-datasource',
},
} as any);
} as DataSourceInstanceSettings);
expect(vizPanelManager.queryRunner.state.datasource).toEqual({
uid: 'gdev-prometheus',
@@ -466,7 +466,7 @@ describe('VizPanelManager', () => {
module: 'prometheus',
id: DASHBOARD_DATASOURCE_PLUGIN_ID,
},
} as any);
} as DataSourceInstanceSettings);
expect(vizPanelManager.queryRunner.state.datasource).toEqual({
uid: SHARED_DASHBOARD_QUERY,
@@ -493,7 +493,7 @@ describe('VizPanelManager', () => {
module: 'prometheus',
id: 'grafana-prometheus-datasource',
},
} as any);
} as DataSourceInstanceSettings);
expect(vizPanelManager.queryRunner.state.datasource).toEqual({
uid: 'gdev-prometheus',

View File

@@ -9,6 +9,7 @@ import {
dateTime,
TimeRange,
PanelMigrationHandler,
PanelTypeChangedHandler,
} from '@grafana/data';
import { getPanelPlugin } from '@grafana/data/test/__mocks__/pluginMocks';
import { mockStandardFieldConfigOptions } from '@grafana/data/test/helpers/fieldConfig';
@@ -43,7 +44,7 @@ variableAdapters.setInit(() => [createQueryVariableAdapter()]);
describe('PanelModel', () => {
describe('when creating new panel model', () => {
let model: any;
let modelJson: any;
let modelJson: Record<string, unknown>;
let persistedOptionsMock;
const tablePlugin = getPanelPlugin(
@@ -388,10 +389,12 @@ describe('PanelModel', () => {
});
describe('when changing to react panel from angular panel', () => {
let panelQueryRunner: any;
let panelQueryRunner: PanelQueryRunner;
const onPanelTypeChanged = jest.fn();
const reactPlugin = getPanelPlugin({ id: 'react' }).setPanelChangeHandler(onPanelTypeChanged as any);
const reactPlugin = getPanelPlugin({ id: 'react' }).setPanelChangeHandler(
onPanelTypeChanged as PanelTypeChangedHandler
);
beforeEach(() => {
model.changePlugin(reactPlugin);
@@ -412,13 +415,13 @@ describe('PanelModel', () => {
});
describe('when autoMigrateFrom angular to react', () => {
const onPanelTypeChanged = (panel: PanelModel, prevPluginId: string, prevOptions: Record<string, any>) => {
const onPanelTypeChanged: PanelTypeChangedHandler = (panel, prevPluginId, prevOptions) => {
panel.fieldConfig = { defaults: { unit: 'bytes' }, overrides: [] };
return { name: prevOptions.angular.oldName };
};
const reactPlugin = getPanelPlugin({ id: 'timeseries' })
.setPanelChangeHandler(onPanelTypeChanged as any)
.setPanelChangeHandler(onPanelTypeChanged)
.useFieldConfig({
disableStandardOptions: [FieldConfigProperty.Thresholds],
})
@@ -450,10 +453,12 @@ describe('PanelModel', () => {
});
describe('variables interpolation', () => {
let panelQueryRunner: any;
let panelQueryRunner: PanelQueryRunner;
const onPanelTypeChanged = jest.fn();
const reactPlugin = getPanelPlugin({ id: 'react' }).setPanelChangeHandler(onPanelTypeChanged as any);
const reactPlugin = getPanelPlugin({ id: 'react' }).setPanelChangeHandler(
onPanelTypeChanged as PanelTypeChangedHandler
);
beforeEach(() => {
model.changePlugin(reactPlugin);

View File

@@ -2,7 +2,7 @@ import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { Subject } from 'rxjs';
import { FetchError, locationService, setEchoSrv } from '@grafana/runtime';
import { BackendSrv, FetchError, locationService, setEchoSrv } from '@grafana/runtime';
import appEvents from 'app/core/app_events';
import { getBackendSrv } from 'app/core/services/backend_srv';
import { KeybindingSrv } from 'app/core/services/keybindingSrv';
@@ -21,8 +21,8 @@ import { getPreloadedState } from '../../variables/state/helpers';
import { initialTransactionState, variablesInitTransaction } from '../../variables/state/transactionReducer';
import { TransactionStatus } from '../../variables/types';
import { DashboardLoaderSrv, setDashboardLoaderSrv } from '../services/DashboardLoaderSrv';
import { getDashboardSrv, setDashboardSrv } from '../services/DashboardSrv';
import { getTimeSrv, setTimeSrv } from '../services/TimeSrv';
import { DashboardSrv, getDashboardSrv, setDashboardSrv } from '../services/DashboardSrv';
import { getTimeSrv, setTimeSrv, TimeSrv } from '../services/TimeSrv';
import { initDashboard, InitDashboardArgs } from './initDashboard';
import { dashboardInitCompleted, dashboardInitFetching, dashboardInitServices } from './reducers';
@@ -68,8 +68,8 @@ const mockStore = configureMockStore([thunk]);
interface ScenarioContext {
args: InitDashboardArgs;
loaderSrv: any;
backendSrv: any;
loaderSrv: DashboardLoaderSrv;
backendSrv: jest.Mocked<BackendSrv>;
setup: (fn: () => void) => void;
actions: any[];
storeState: any;
@@ -175,14 +175,14 @@ function describeInitScenario(description: string, scenarioFn: ScenarioFn) {
uid: DASH_UID,
},
})),
};
} as unknown as DashboardLoaderSrv;
setDashboardLoaderSrv(loaderSrv as unknown as DashboardLoaderSrv);
setDashboardLoaderSrv(loaderSrv);
setDashboardQueryRunnerFactory(() => ({
getResult: emptyResult,
run: jest.fn(),
cancel: () => undefined,
cancellations: () => new Subject<any>(),
cancellations: () => new Subject(),
destroy: () => undefined,
}));
@@ -197,7 +197,7 @@ function describeInitScenario(description: string, scenarioFn: ScenarioFn) {
setupDashboardBindings: jest.fn(),
} as unknown as KeybindingSrv,
},
backendSrv: getBackendSrv(),
backendSrv: getBackendSrv() as unknown as jest.Mocked<BackendSrv>,
loaderSrv,
actions: [],
storeState: {
@@ -226,11 +226,11 @@ function describeInitScenario(description: string, scenarioFn: ScenarioFn) {
beforeEach(async () => {
setDashboardSrv({
setCurrent: jest.fn(),
} as any);
} as unknown as DashboardSrv);
setTimeSrv({
init: jest.fn(),
} as any);
} as unknown as TimeSrv);
setupFn();
setEchoSrv(new Echo());

View File

@@ -1,8 +1,9 @@
import { thunkTester } from 'test/core/thunk/thunkTester';
import { AppPluginMeta, DataSourceSettings, PluginMetaInfo, PluginType } from '@grafana/data';
import { FetchError } from '@grafana/runtime';
import { DataSourceSrv, FetchError } from '@grafana/runtime';
import { appEvents } from 'app/core/core';
import { getBackendSrv } from 'app/core/services/backend_srv';
import { ThunkResult, ThunkDispatch } from 'app/types';
import { getMockDataSource } from '../__mocks__';
@@ -55,7 +56,7 @@ const getBackendSrvMock = () =>
}),
}),
withNoBackendCache: jest.fn().mockImplementationOnce((cb) => cb()),
}) as any;
}) as unknown as ReturnType<typeof getBackendSrv>;
const failDataSourceTest = async (error: object) => {
const dependencies: TestDataSourceDependencies = {
@@ -66,7 +67,7 @@ const failDataSourceTest = async (error: object) => {
throw error;
}),
}),
}) as any,
}) as Pick<DataSourceSrv, 'get'>,
getBackendSrv: getBackendSrvMock,
};
const state = {
@@ -228,7 +229,7 @@ describe('testDataSource', () => {
type: 'cloudwatch',
uid: 'CW1234',
}),
}) as any,
}) as Pick<DataSourceSrv, 'get'>,
getBackendSrv: getBackendSrvMock,
};
const state = {
@@ -263,7 +264,7 @@ describe('testDataSource', () => {
type: 'azure-monitor',
uid: 'azM0nit0R',
}),
}) as any,
}) as Pick<DataSourceSrv, 'get'>,
getBackendSrv: getBackendSrvMock,
};
const result = {

View File

@@ -2,6 +2,7 @@ import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { Provider } from 'react-redux';
import { DataSourceApi } from '@grafana/data';
import { DataSourceSrv, setDataSourceSrv } from '@grafana/runtime';
import { DataQuery } from '@grafana/schema';
import { configureStore } from 'app/store/configureStore';
@@ -22,9 +23,9 @@ function setup(queries: DataQuery[]) {
name: 'newDs',
uid: 'newDs-uid',
meta: { id: 'newDs' },
};
} as DataSourceApi;
const datasources: Record<string, any> = {
const datasources: Record<string, DataSourceApi> = {
'newDs-uid': defaultDs,
'someDs-uid': {
name: 'someDs',
@@ -33,7 +34,7 @@ function setup(queries: DataQuery[]) {
components: {
QueryEditor: () => 'someDs query editor',
},
},
} as unknown as DataSourceApi,
};
setDataSourceSrv({
@@ -46,7 +47,7 @@ function setup(queries: DataQuery[]) {
get(uid?: string) {
return Promise.resolve(uid ? datasources[uid] || defaultDs : defaultDs);
},
} as DataSourceSrv);
} as unknown as DataSourceSrv);
const leftState = makeExplorePaneState();
const initialState: ExploreState = {

View File

@@ -63,7 +63,7 @@ describe('processTemplate()', () => {
expect(() =>
processTemplate(
{
template: (data: { [key: string]: any }) => `a${data.b}c`,
template: (data: { [key: string]: unknown }) => `a${data.b}c`,
},
(a) => a
)

View File

@@ -1,4 +1,5 @@
import React from 'react';
import { Props } from 'react-virtualized-auto-sizer';
import { DataQueryRequest, EventBusSrv, serializeStateToUrlParam } from '@grafana/data';
import { getTemplateSrv } from '@grafana/runtime';
@@ -25,8 +26,8 @@ jest.mock('app/core/core', () => ({
jest.mock('react-virtualized-auto-sizer', () => {
return {
__esModule: true,
default(props: any) {
return <div>{props.children({ width: 1000 })}</div>;
default(props: Props) {
return <div>{props.children({ height: 1, scaledHeight: 1, scaledWidth: 1000, width: 1000 })}</div>;
},
};
});

View File

@@ -1,4 +1,5 @@
import React from 'react';
import { Props } from 'react-virtualized-auto-sizer';
import { EventBusSrv, serializeStateToUrlParam } from '@grafana/data';
import { config } from '@grafana/runtime';
@@ -73,8 +74,8 @@ jest.mock('app/core/services/PreferencesService', () => ({
jest.mock('react-virtualized-auto-sizer', () => {
return {
__esModule: true,
default(props: any) {
return <div>{props.children({ width: 1000 })}</div>;
default(props: Props) {
return <div>{props.children({ height: 1, scaledHeight: 1, scaledWidth: 1000, width: 1000 })}</div>;
},
};
});

View File

@@ -4,7 +4,7 @@ import countriesJSON from '../../../../gazetteer/countries.json';
import { getGazetteer } from './gazetteer';
let backendResults: any = { hello: 'world' };
let backendResults: Record<string, string> | Array<Record<string, unknown>> = { hello: 'world' };
jest.mock('@grafana/runtime', () => ({
...jest.requireActual('@grafana/runtime'),

View File

@@ -40,7 +40,7 @@ describe('importDashboard', () => {
},
};
let postArgs: any;
let postArgs: unknown;
setBackendSrv({
post: (url, args) => {

View File

@@ -1,5 +1,6 @@
import { AlertState, AlertStateInfo, getDefaultTimeRange, TimeRange } from '@grafana/data';
import { backendSrv } from 'app/core/services/backend_srv';
import { DashboardModel } from 'app/features/dashboard/state';
import { silenceConsoleOutput } from '../../../../../test/core/utils/silenceConsoleOutput';
import * as store from '../../../../store/store';
@@ -13,7 +14,7 @@ jest.mock('@grafana/runtime', () => ({
}));
function getDefaultOptions(): DashboardQueryRunnerOptions {
const dashboard: any = { id: 'an id', panels: [{ alert: {} }] };
const dashboard = { id: 'an id', panels: [{ alert: {} }] } as DashboardModel;
const range = getDefaultTimeRange();
return { dashboard, range };
@@ -41,7 +42,7 @@ describe('AlertStatesWorker', () => {
describe('when canWork is called with no dashboard id', () => {
it('then it should return false', () => {
const dashboard: any = {};
const dashboard = {} as DashboardModel;
const options = { ...getDefaultOptions(), dashboard };
expect(worker.canWork(options)).toBe(false);
@@ -69,7 +70,7 @@ describe('AlertStatesWorker', () => {
describe('when run is called with incorrect props', () => {
it('then it should return the correct results', async () => {
const { getMock, options } = getTestContext();
const dashboard: any = {};
const dashboard = {} as DashboardModel;
await expect(worker.work({ ...options, dashboard })).toEmitValuesWith((received) => {
expect(received).toHaveLength(1);

View File

@@ -1,6 +1,7 @@
import { Observable, of, throwError } from 'rxjs';
import { AnnotationQuery, DataSourceApi, getDefaultTimeRange } from '@grafana/data';
import { AnnotationQueryResponse } from 'app/features/annotations/types';
import { createDashboardModelFixture } from 'app/features/dashboard/state/__fixtures__/dashboardFixtures';
import { silenceConsoleOutput } from '../../../../../test/core/utils/silenceConsoleOutput';
@@ -23,7 +24,7 @@ function getDefaultOptions(): AnnotationQueryRunnerOptions {
return { annotation, datasource, dashboard, range };
}
function getTestContext(result: Observable<any> = toAsyncOfResult({ events: [{ id: '1' }] })) {
function getTestContext(result: Observable<AnnotationQueryResponse> = toAsyncOfResult({ events: [{ id: '1' }] })) {
jest.clearAllMocks();
const dispatchMock = jest.spyOn(store, 'dispatch');
const options = getDefaultOptions();
@@ -94,7 +95,7 @@ describe('AnnotationsQueryRunner', () => {
describe('but result is missing events prop', () => {
it('then it should return the correct results', async () => {
const { options, executeAnnotationQueryMock } = getTestContext(of({ id: '1' }));
const { options, executeAnnotationQueryMock } = getTestContext(of({ id: '1' } as AnnotationQueryResponse));
await expect(runner.run(options)).toEmitValuesWith((received) => {
expect(received).toHaveLength(1);

View File

@@ -45,7 +45,7 @@ describe('__url_time_range', () => {
from: 1607687293000,
to: 1607687293100,
}),
} as any);
} as unknown as TimeSrv);
});
it('should interpolate to url params', () => {

View File

@@ -48,24 +48,24 @@ describe('optionsPickerReducer', () => {
];
const expectToggleOptionState = (args: {
options: any;
multi: any;
forceSelect: any;
clearOthers: any;
option: any;
expectSelected: any;
options: typeof opsAll;
multi: boolean;
forceSelect: boolean;
clearOthers: boolean;
option: string;
expectSelected: string[];
}) => {
const { initialState } = getVariableTestContext({
options: args.options,
multi: args.multi,
selectedValues: args.options.filter((o: any) => o.selected),
selectedValues: args.options.filter((o) => o.selected),
});
const payload = {
forceSelect: args.forceSelect,
clearOthers: args.clearOthers,
option: { text: args.option, value: args.option, selected: true },
};
const expectedAsRecord = args.expectSelected.reduce((all: any, current: any) => {
const expectedAsRecord = args.expectSelected.reduce<Record<string, string>>((all, current) => {
all[current] = current;
return all;
}, {});
@@ -75,8 +75,8 @@ describe('optionsPickerReducer', () => {
.whenActionIsDispatched(toggleOption(payload))
.thenStateShouldEqual({
...initialState,
selectedValues: args.expectSelected.map((value: any) => ({ value, text: value, selected: true })),
options: args.options.map((option: any) => {
selectedValues: args.expectSelected.map((value) => ({ value, text: value, selected: true })),
options: args.options.map((option) => {
return { ...option, selected: !!expectedAsRecord[option.value] };
}),
});
@@ -124,7 +124,17 @@ describe('optionsPickerReducer', () => {
${'$__all'} | ${false} | ${true} | ${['$__all']}
`(
'and we toggle $option with options: { forceSelect: $forceSelect, clearOthers: $clearOthers } we expect $expectSelected to be selected',
({ option, forceSelect, clearOthers, expectSelected }) =>
({
option,
forceSelect,
clearOthers,
expectSelected,
}: {
option: string;
forceSelect: boolean;
clearOthers: boolean;
expectSelected: string[];
}) =>
expectToggleOptionState({
options,
multi,
@@ -309,7 +319,7 @@ describe('optionsPickerReducer', () => {
describe('when showOptions is dispatched and queryValue and variable has no searchFilter', () => {
it('then state should be correct', () => {
const query = '*.';
const queryValue: any = null;
const queryValue = null;
const current = { text: ALL_VARIABLE_TEXT, selected: true, value: [ALL_VARIABLE_VALUE] };
const options = [
{ text: 'All', value: '$__all', selected: true },
@@ -317,7 +327,7 @@ describe('optionsPickerReducer', () => {
{ text: 'B', value: 'B', selected: false },
];
const { initialState } = getVariableTestContext({});
const payload = { type: 'query', id: '0', current, query, options, queryValue } as QueryVariableModel;
const payload = { type: 'query', id: '0', current, query, options, queryValue } as unknown as QueryVariableModel;
reducerTester<OptionsPickerState>()
.givenReducer(optionsPickerReducer, cloneDeep(initialState))
@@ -546,11 +556,11 @@ describe('optionsPickerReducer', () => {
it('then state should be correct', () => {
const queryValue = 'A';
const options: any = [
const options = [
{ text: 'All', value: '$__all', selected: true },
{ text: null, value: null, selected: false },
{ text: [null], value: [null], selected: false },
];
] as VariableOption[];
const { initialState } = getVariableTestContext({ queryValue });

View File

@@ -1,7 +1,7 @@
import React from 'react';
import { DataSourceRef, getDefaultTimeRange, LoadingState } from '@grafana/data';
import { setDataSourceSrv } from '@grafana/runtime';
import { DataSourceApi, DataSourceRef, getDefaultTimeRange, LoadingState } from '@grafana/data';
import { DataSourceSrv, setDataSourceSrv } from '@grafana/runtime';
import { reduxTester } from '../../../../test/core/redux/reduxTester';
import { silenceConsoleOutput } from '../../../../test/core/utils/silenceConsoleOutput';
@@ -60,7 +60,7 @@ const mocks: Record<string, any> = {
},
};
setDataSourceSrv(mocks.dataSourceSrv as any);
setDataSourceSrv(mocks.dataSourceSrv as DataSourceSrv);
jest.mock('../../plugins/plugin_loader', () => ({
importDataSourcePlugin: () => mocks.pluginLoader.importDataSourcePlugin(),
@@ -353,7 +353,7 @@ describe('query actions', () => {
it('then correct actions are dispatched', async () => {
const variable = createVariable({ datasource: { uid: 'other' } });
const editor = mocks.VariableQueryEditor;
const previousDataSource: any = { type: 'previous' };
const previousDataSource = { type: 'previous' } as DataSourceApi;
const templatingState = {
editor: {
...initialVariableEditorState,
@@ -843,8 +843,8 @@ describe('query actions', () => {
});
});
function mockDatasourceMetrics(variable: QueryVariableModel, optionsMetrics: any[]) {
const metrics: Record<string, any[]> = {
function mockDatasourceMetrics(variable: QueryVariableModel, optionsMetrics: unknown[]) {
const metrics: Record<string, unknown[]> = {
[variable.query]: optionsMetrics,
};

View File

@@ -1,10 +1,10 @@
import { of } from 'rxjs';
import { getDefaultTimeRange, VariableSupportType } from '@grafana/data';
import { DataQueryRequest, getDefaultTimeRange, QueryVariableModel, VariableSupportType } from '@grafana/data';
import { VariableRefresh } from '../types';
import { QueryRunners, variableDummyRefId } from './queryRunners';
import { QueryRunners, RunnerArgs, variableDummyRefId } from './queryRunners';
describe('QueryRunners', () => {
describe('when using a legacy data source', () => {
@@ -17,8 +17,14 @@ describe('QueryRunners', () => {
const datasource: any = { metricFindQuery: jest.fn().mockResolvedValue([{ text: 'A', value: 'A' }]) };
const runner = new QueryRunners().getRunnerForDatasource(datasource);
const runRequest = jest.fn().mockReturnValue(of({}));
const runnerArgs: any = { datasource, variable, searchFilter: 'A searchFilter', timeSrv, runRequest };
const request: any = {};
const runnerArgs = {
datasource,
variable,
searchFilter: 'A searchFilter',
timeSrv,
runRequest,
} as unknown as RunnerArgs;
const request = {} as DataQueryRequest;
return { timeSrv, datasource, runner, variable, runnerArgs, request, defaultTimeRange };
};
@@ -146,7 +152,7 @@ describe('QueryRunners', () => {
describe('when using a data source with standard variable support', () => {
const getStandardTestContext = (datasource?: any) => {
const variable: any = { query: { refId: 'A', query: 'A query' } };
const variable = { query: { refId: 'A', query: 'A query' } } as QueryVariableModel;
const timeSrv = {};
datasource = datasource ?? {
variables: {
@@ -156,8 +162,14 @@ describe('QueryRunners', () => {
};
const runner = new QueryRunners().getRunnerForDatasource(datasource);
const runRequest = jest.fn().mockReturnValue(of({}));
const runnerArgs: any = { datasource, variable, searchFilter: 'A searchFilter', timeSrv, runRequest };
const request: any = {};
const runnerArgs = {
datasource,
variable,
searchFilter: 'A searchFilter',
timeSrv,
runRequest,
} as unknown as RunnerArgs;
const request = {} as DataQueryRequest;
return { timeSrv, datasource, runner, variable, runnerArgs, request, runRequest };
};
@@ -222,15 +234,21 @@ describe('QueryRunners', () => {
describe('when using a data source with custom variable support', () => {
const getCustomTestContext = () => {
const variable: any = { query: { refId: 'A', query: 'A query' } };
const variable = { query: { refId: 'A', query: 'A query' } } as QueryVariableModel;
const timeSrv = {};
const datasource: any = {
variables: { getType: () => VariableSupportType.Custom, query: () => undefined, editor: {} },
};
const runner = new QueryRunners().getRunnerForDatasource(datasource);
const runRequest = jest.fn().mockReturnValue(of({}));
const runnerArgs: any = { datasource, variable, searchFilter: 'A searchFilter', timeSrv, runRequest };
const request: any = {};
const runnerArgs = {
datasource,
variable,
searchFilter: 'A searchFilter',
timeSrv,
runRequest,
} as unknown as RunnerArgs;
const request = {} as DataQueryRequest;
return { timeSrv, datasource, runner, variable, runnerArgs, request, runRequest };
};
@@ -270,15 +288,21 @@ describe('QueryRunners', () => {
describe('when using a data source with datasource variable support', () => {
const getDatasourceTestContext = () => {
const variable: any = { query: { refId: 'A', query: 'A query' } };
const variable = { query: { refId: 'A', query: 'A query' } } as QueryVariableModel;
const timeSrv = {};
const datasource: any = {
variables: { getType: () => VariableSupportType.Datasource },
};
const runner = new QueryRunners().getRunnerForDatasource(datasource);
const runRequest = jest.fn().mockReturnValue(of({}));
const runnerArgs: any = { datasource, variable, searchFilter: 'A searchFilter', timeSrv, runRequest };
const request: any = {};
const runnerArgs = {
datasource,
variable,
searchFilter: 'A searchFilter',
timeSrv,
runRequest,
} as unknown as RunnerArgs;
const request = {} as DataQueryRequest;
return { timeSrv, datasource, runner, variable, runnerArgs, request, runRequest };
};

View File

@@ -1,9 +1,12 @@
import { createAction } from '@reduxjs/toolkit';
import { ComponentType } from 'react';
import { VariableType } from '@grafana/data';
import { reducerTester } from '../../../../test/core/redux/reducerTester';
import { VariableAdapter, variableAdapters } from '../adapters';
import { VariableEditorProps } from '../editor/types';
import { VariablePickerProps } from '../pickers/types';
import { QueryVariableModel } from '../types';
import { toVariablePayload } from '../utils';
@@ -21,8 +24,8 @@ const variableAdapter: VariableAdapter<QueryVariableModel> = {
reducer: jest.fn().mockReturnValue({}),
getValueForUrl: jest.fn(),
getSaveModel: jest.fn(),
picker: null as any,
editor: null as any,
picker: null as unknown as ComponentType<VariablePickerProps<QueryVariableModel>>,
editor: null as unknown as ComponentType<VariableEditorProps<QueryVariableModel>>,
setValue: jest.fn(),
setValueFromUrl: jest.fn(),
};

View File

@@ -10,6 +10,7 @@ import {
variablesCompleteTransaction,
variablesInitTransaction,
} from './transactionReducer';
import { VariablePayload } from './types';
describe('transactionReducer', () => {
describe('when variablesInitTransaction is dispatched', () => {
@@ -71,7 +72,7 @@ describe('transactionReducer', () => {
...initialTransactionState,
status: TransactionStatus.Fetching,
})
.whenActionIsDispatched(removeVariable({} as any))
.whenActionIsDispatched(removeVariable({} as VariablePayload<{ reIndex: boolean }>))
.thenStateShouldEqual({ uid: null, status: TransactionStatus.Fetching, isDirty: false });
});
});
@@ -83,7 +84,7 @@ describe('transactionReducer', () => {
...initialTransactionState,
status: TransactionStatus.NotStarted,
})
.whenActionIsDispatched(removeVariable({} as any))
.whenActionIsDispatched(removeVariable({} as VariablePayload<{ reIndex: boolean }>))
.thenStateShouldEqual({ uid: null, status: TransactionStatus.NotStarted, isDirty: false });
});
});
@@ -95,7 +96,7 @@ describe('transactionReducer', () => {
...initialTransactionState,
status: TransactionStatus.Completed,
})
.whenActionIsDispatched(removeVariable({} as any))
.whenActionIsDispatched(removeVariable({} as VariablePayload<{ reIndex: boolean }>))
.thenStateShouldEqual({ uid: null, status: TransactionStatus.Completed, isDirty: true });
});
});
@@ -107,7 +108,7 @@ describe('transactionReducer', () => {
...initialTransactionState,
status: TransactionStatus.Completed,
})
.whenActionIsDispatched(variableStateNotStarted({} as any))
.whenActionIsDispatched(variableStateNotStarted({} as VariablePayload))
.thenStateShouldEqual({ uid: null, status: TransactionStatus.Completed, isDirty: false });
});
});

View File

@@ -19,11 +19,11 @@ describe('ElasticQueryBuilder', () => {
it('should clean settings from null values', () => {
const query = builder.build({
refId: 'A',
// The following `missing: null as any` is because previous versions of the DS where
// The following `missing: null as unknown as string` is because previous versions of the DS where
// storing null in the query model when inputting an empty string,
// which were then removed in the query builder.
// The new version doesn't store empty strings at all. This tests ensures backward compatibility.
metrics: [{ type: 'avg', id: '0', settings: { missing: null as any, script: '1' } }],
metrics: [{ type: 'avg', id: '0', settings: { missing: null as unknown as string, script: '1' } }],
timeField: '@timestamp',
bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '1' }],
});

View File

@@ -22,7 +22,7 @@ describe('grafana data source', () => {
});
describe('when executing an annotations query', () => {
let calledBackendSrvParams: any;
let calledBackendSrvParams: Parameters<(typeof backendSrv)['get']>[1];
let ds: GrafanaDatasource;
beforeEach(() => {
getMock.mockImplementation((url, options) => {
@@ -41,7 +41,7 @@ describe('grafana data source', () => {
});
it('should interpolate template variables in tags in query options', () => {
expect(calledBackendSrvParams.tags[0]).toBe('tag1:replaced');
expect(calledBackendSrvParams?.tags[0]).toBe('tag1:replaced');
});
});
@@ -53,8 +53,8 @@ describe('grafana data source', () => {
});
it('should interpolate template variables in tags in query options', () => {
expect(calledBackendSrvParams.tags[0]).toBe('replaced');
expect(calledBackendSrvParams.tags[1]).toBe('replaced2');
expect(calledBackendSrvParams?.tags[0]).toBe('replaced');
expect(calledBackendSrvParams?.tags[1]).toBe('replaced2');
});
});
@@ -72,7 +72,7 @@ describe('grafana data source', () => {
});
it('should remove tags from query options', () => {
expect(calledBackendSrvParams.tags).toBe(undefined);
expect(calledBackendSrvParams?.tags).toBe(undefined);
});
});
});

View File

@@ -2,7 +2,14 @@ import { isArray } from 'lodash';
import { of } from 'rxjs';
import { createFetchResponse } from 'test/helpers/createFetchResponse';
import { AbstractLabelMatcher, AbstractLabelOperator, getFrameDisplayName, dateTime } from '@grafana/data';
import {
AbstractLabelMatcher,
AbstractLabelOperator,
getFrameDisplayName,
dateTime,
DataQueryRequest,
MetricFindValue,
} from '@grafana/data';
import { BackendSrvRequest } from '@grafana/runtime';
import { backendSrv } from 'app/core/services/backend_srv'; // will use the version in __mocks__
import { TemplateSrv } from 'app/features/templating/template_srv';
@@ -120,7 +127,7 @@ describe('graphiteDatasource', () => {
maxDataPoints: 500,
};
let response: any;
let response: unknown;
let requestOptions: BackendSrvRequest;
beforeEach(() => {
@@ -139,7 +146,7 @@ describe('graphiteDatasource', () => {
);
});
response = ctx.ds.query(query as any);
response = ctx.ds.query(query as unknown as DataQueryRequest<GraphiteQuery>);
});
it('X-Dashboard and X-Panel headers to be set!', () => {
@@ -411,7 +418,7 @@ describe('graphiteDatasource', () => {
});
describe('querying for template variables', () => {
let results: any;
let results: MetricFindValue[];
let requestOptions: BackendSrvRequest;
beforeEach(() => {
@@ -503,7 +510,7 @@ describe('graphiteDatasource', () => {
current: { value: ['bar'] },
},
]);
ctx.ds.metricFindQuery('[[foo]]').then((data: any) => {
ctx.ds.metricFindQuery('[[foo]]').then((data) => {
results = data;
});
expect(requestOptions.url).toBe('/api/datasources/proxy/1/metrics/find');

View File

@@ -5,9 +5,11 @@ import {
AnnotationEvent,
AnnotationQueryRequest,
CoreApp,
CustomVariableModel,
DataQueryRequest,
DataSourceInstanceSettings,
dateTime,
LoadingState,
rangeUtil,
TimeRange,
VariableHide,
@@ -463,7 +465,7 @@ describe('PrometheusDatasource', () => {
});
describe('When interpolating variables', () => {
let customVariable: any;
let customVariable: CustomVariableModel;
beforeEach(() => {
customVariable = {
id: '',
@@ -476,11 +478,14 @@ describe('PrometheusDatasource', () => {
current: {},
name: '',
type: 'custom',
label: null,
error: null,
rootStateKey: '',
state: LoadingState.Done,
description: '',
label: undefined,
hide: VariableHide.dontHide,
skipUrlSync: false,
index: -1,
initLock: null,
};
});
@@ -492,7 +497,7 @@ describe('PrometheusDatasource', () => {
describe('and value is a number', () => {
it('should return a number', () => {
expect(ds.interpolateQueryExpr(1000 as any, customVariable)).toEqual(1000);
expect(ds.interpolateQueryExpr(1000 as unknown as string, customVariable)).toEqual(1000);
});
});
@@ -863,7 +868,7 @@ describe('PrometheusDatasource2', () => {
});
describe('region annotations for sectors', () => {
const options: any = {
const options = {
annotation: {
expr: 'ALERTS{alertstate="firing"}',
tagKeys: 'job',
@@ -874,7 +879,7 @@ describe('PrometheusDatasource2', () => {
from: time({ seconds: 63 }),
to: time({ seconds: 900 }),
},
};
} as unknown as AnnotationQueryRequest;
async function runAnnotationQuery(data: number[][]) {
let response = createAnnotationResponse();

View File

@@ -58,7 +58,15 @@ describe('PrometheusMetricFindQuery', () => {
);
});
const setupMetricFindQuery = (data: any, datasource?: PrometheusDatasource) => {
const setupMetricFindQuery = (
data: {
query: string;
response: {
data: unknown;
};
},
datasource?: PrometheusDatasource
) => {
fetchMock.mockImplementation(() => of({ status: 'success', data: data.response } as unknown as FetchResponse));
return new PrometheusMetricFindQuery(datasource ?? legacyPrometheusDatasource, data.query);
};

View File

@@ -909,7 +909,7 @@ describe('Prometheus Result Transformer', () => {
},
],
} as unknown as DataQueryRequest<PromQuery>;
const testOptions: any = {
const testOptions = {
exemplarTraceIdDestinations: [
{
name: 'traceID',

View File

@@ -14,6 +14,7 @@ import {
DataSourceApi,
DataQueryRequest,
getTimeZone,
PluginMetaInfo,
} from '@grafana/data';
import {
BackendDataSourceResponse,
@@ -46,7 +47,7 @@ import { createMetadataRequest, createTempoDatasource } from './mocks';
import { initTemplateSrv } from './test_utils';
import { TempoJsonData, TempoQuery } from './types';
let mockObservable: () => Observable<any>;
let mockObservable: () => Observable<unknown>;
jest.mock('@grafana/runtime', () => {
return {
...jest.requireActual('@grafana/runtime'),
@@ -68,7 +69,9 @@ describe('Tempo data source', () => {
const templateSrv: TemplateSrv = { replace: jest.fn() } as unknown as TemplateSrv;
const ds = new TempoDatasource(defaultSettings, templateSrv);
const response = await lastValueFrom(
ds.query({ targets: [{ refId: 'refid1', queryType: 'traceql', query: '' } as Partial<TempoQuery>] } as any),
ds.query({
targets: [{ refId: 'refid1', queryType: 'traceql', query: '' } as Partial<TempoQuery>],
} as DataQueryRequest<TempoQuery>),
{ defaultValue: 'empty' }
);
expect(response).toBe('empty');
@@ -168,9 +171,11 @@ describe('Tempo data source', () => {
],
})
);
const templateSrv: any = { replace: jest.fn() };
const templateSrv = { replace: jest.fn() } as unknown as TemplateSrv;
const ds = new TempoDatasource(defaultSettings, templateSrv);
const response = await lastValueFrom(ds.query({ targets: [{ refId: 'refid1', query: '12345' }] } as any));
const response = await lastValueFrom(
ds.query({ targets: [{ refId: 'refid1', query: '12345' }] } as DataQueryRequest<TempoQuery>)
);
expect(
(response.data[0] as DataFrame).fields.map((f) => ({
@@ -222,7 +227,7 @@ describe('Tempo data source', () => {
const response = await lastValueFrom(
ds.query({
targets: [{ queryType: 'upload', refId: 'A' }],
} as any)
} as DataQueryRequest<TempoQuery>)
);
const field = response.data[0].fields[0];
expect(field.name).toBe('traceID');
@@ -237,7 +242,7 @@ describe('Tempo data source', () => {
const response = await lastValueFrom(
ds.query({
targets: [{ queryType: 'upload', refId: 'A' }],
} as any)
} as DataQueryRequest<TempoQuery>)
);
expect(response.error?.message).toBeDefined();
expect(response.data.length).toBe(0);
@@ -249,7 +254,7 @@ describe('Tempo data source', () => {
const response = await lastValueFrom(
ds.query({
targets: [{ queryType: 'upload', refId: 'A' }],
} as any)
} as DataQueryRequest<TempoQuery>)
);
expect(response.data).toHaveLength(2);
const nodesFrame = response.data[0];
@@ -262,10 +267,9 @@ describe('Tempo data source', () => {
});
it('should build search query correctly', () => {
const templateSrv: any = { replace: jest.fn() };
const ds = new TempoDatasource(defaultSettings, templateSrv);
const duration = '10ms';
templateSrv.replace.mockReturnValue(duration);
const templateSrv = { replace: jest.fn().mockReturnValue(duration) } as unknown as TemplateSrv;
const ds = new TempoDatasource(defaultSettings, templateSrv);
const tempoQuery: TempoQuery = {
queryType: 'search',
refId: 'A',
@@ -492,7 +496,11 @@ describe('Tempo service graph view', () => {
});
setDataSourceSrv(dataSourceSrvWithPrometheus(prometheusMock()));
const response = await lastValueFrom(
ds.query({ targets: [{ queryType: 'serviceMap' }], range: getDefaultTimeRange(), app: CoreApp.Explore } as any)
ds.query({
targets: [{ queryType: 'serviceMap' }],
range: getDefaultTimeRange(),
app: CoreApp.Explore,
} as DataQueryRequest<TempoQuery>)
);
expect(response.data).toHaveLength(3);
@@ -1190,7 +1198,7 @@ export const defaultSettings: DataSourceInstanceSettings<TempoJsonData> = {
id: 'tempo',
name: 'tempo',
type: PluginType.datasource,
info: {} as any,
info: {} as PluginMetaInfo,
module: '',
baseUrl: '',
},

View File

@@ -7,7 +7,7 @@ import { locationService } from '@grafana/runtime';
import { silenceConsoleOutput } from '../../../../test/core/utils/silenceConsoleOutput';
import { backendSrv } from '../../../core/services/backend_srv';
import { setDashboardSrv } from '../../../features/dashboard/services/DashboardSrv';
import { DashboardSrv, setDashboardSrv } from '../../../features/dashboard/services/DashboardSrv';
import { AnnoListPanel, Props } from './AnnoListPanel';
import { Options } from './panelcfg.gen';
@@ -56,7 +56,7 @@ async function setupTestContext({
getMock.mockResolvedValue(results);
const dash = { uid: 'srx16xR4z', formatDate: (time: number) => new Date(time).toISOString() };
const dashSrv: any = { getCurrent: () => dash };
const dashSrv = { getCurrent: () => dash } as DashboardSrv;
setDashboardSrv(dashSrv);
const pushSpy = jest.spyOn(locationService, 'push');
@@ -64,10 +64,9 @@ async function setupTestContext({
data: { state: LoadingState.Done, timeRange: getDefaultTimeRange(), series: [] },
eventBus: {
subscribe: jest.fn(),
getStream: () =>
({
subscribe: jest.fn(),
}) as any,
getStream: jest.fn().mockImplementation(() => ({
subscribe: jest.fn(),
})),
publish: jest.fn(),
removeAllListeners: jest.fn(),
newScopedBus: jest.fn(),