Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tests for React Data Source #113

Merged
merged 10 commits into from
Dec 22, 2020
File renamed without changes.
7 changes: 4 additions & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
const standard = require('@grafana/toolkit/src/config/jest.plugin.config');

// This process will use the same config that `yarn test` is using
const grafanaJestConfig = standard.jestConfig();
const grafanaJestConfig = standard.jestConfig('');
module.exports = {
...grafanaJestConfig,
setupFiles: ['./src/tests.ts'].concat(grafanaJestConfig.setupFiles ? grafanaJestConfig.setupFiles : []),
collectCoverage: true,
coveragePathIgnorePatterns: ['node_modules', 'src/tests'].concat(
grafanaJestConfig.coveragePathIgnorePatterns ? grafanaJestConfig.coveragePathIgnorePatterns : []
),
};
27 changes: 2 additions & 25 deletions src/components/query-editor.test.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,8 @@
import React from 'react';
import { shallow, ShallowWrapper } from 'enzyme';
import { QueryEditor } from './query-editor';
import { AggregationValue, InfoSectionValue, QueryTypeValue, RedisQuery } from '../redis';

/**
* Query
*/
const getQuery = (overrideQuery: object = {}): RedisQuery => ({
keyName: '',
aggregation: AggregationValue.NONE,
bucket: 0,
legend: '',
command: '',
field: '',
filter: '',
value: '',
query: '',
type: QueryTypeValue.CLI,
section: InfoSectionValue.STATS,
size: 1,
fill: true,
streaming: true,
streamingInterval: 1,
streamingCapacity: 1,
refId: '',
...overrideQuery,
});
import { QueryTypeValue } from '../redis';
import { getQuery } from '../tests/utils';

type ShallowComponent = ShallowWrapper<QueryEditor['props'], QueryEditor['state'], QueryEditor>;

Expand Down
254 changes: 254 additions & 0 deletions src/data-source.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
import {
DataQueryRequest,
DataSourceInstanceSettings,
PluginType,
CircularDataFrame,
MetricFindValue,
} from '@grafana/data';
import { Observable } from 'rxjs';
import { take } from 'rxjs/operators';
import { DataSourceWithBackend, setTemplateSrv, TemplateSrv } from '@grafana/runtime';
import { DataSource } from './data-source';
import { QueryTypeValue, RedisQuery } from './redis';
import { ClientTypeValue, RedisDataSourceOptions } from './types';
import { getQuery } from './tests/utils';

/**
* Instance Settings
*/
const getInstanceSettings = (overrideSettings: object = {}): DataSourceInstanceSettings<RedisDataSourceOptions> => ({
uid: '',
id: 1,
type: '',
name: '',
meta: {
id: '',
name: '',
type: PluginType.datasource,
info: {} as any,
module: '',
baseUrl: '',
},
jsonData: {
poolSize: 0,
timeout: 0,
pingInterval: 0,
pipelineWindow: 0,
tlsAuth: false,
tlsSkipVerify: false,
client: ClientTypeValue.CLUSTER,
sentinelName: '',
acl: false,
user: '',
},
});

/**
* Override Request
*/
interface OverrideRequest {
[key: string]: unknown;
targets?: RedisQuery[];
}

/**
* Request
*/
const getRequest = (overrideRequest: OverrideRequest = {}): DataQueryRequest<RedisQuery> => ({
requestId: '',
interval: '',
intervalMs: 0,
range: {} as any,
scopedVars: {},
timezone: '',
app: '',
startTime: 0,
...overrideRequest,
targets: overrideRequest.targets
? overrideRequest.targets
: [
{
datasource: '',
type: QueryTypeValue.CLI,
refId: 'A',
query: '',
streaming: false,
},
],
});

/**
* Data Source
*/
describe('DataSource', () => {
const superQueryMock = jest.spyOn(DataSourceWithBackend.prototype, 'query').mockImplementation(
() =>
new Observable((subscriber) => {
subscriber.next({
data: [
{
fields: [
{
name: 'get',
values: {
toArray() {
return [1, 2, 3];
},
},
},
],
length: 1,
},
],
});
subscriber.complete();
})
);
const instanceSettings = getInstanceSettings();
let dataSource: DataSource;
let templateSrv: TemplateSrv;

beforeEach(() => {
superQueryMock.mockClear();
dataSource = new DataSource(instanceSettings);
templateSrv = {
replace: jest.fn().mockImplementation((value) => `replaced:${value}`),
getVariables: jest.fn(),
};
setTemplateSrv(templateSrv);
});

/**
* Query Method
*/
describe('query', () => {
it('If no streaming should use super.query', (done) => {
const request = getRequest();
dataSource.query(request).subscribe(() => {
expect(superQueryMock).toHaveBeenCalledWith(request);
done();
});
});

it('If streaming exists should get frames in interval', (done) => {
const request = getRequest({
targets: [
{
datasource: '',
type: QueryTypeValue.CLI,
refId: 'A',
query: '',
streaming: true,
streamingCapacity: 1,
},
],
});
dataSource
.query(request)
.pipe(take(3))
.subscribe(
(value) => {
value.data.forEach((item) => {
expect(item).toBeInstanceOf(CircularDataFrame);
});
},
null,
() => {
done();
}
);
});
});

/**
* ApplyTemplateVariables Method
*/
describe('applyTemplateVariables', () => {
type KeyType = keyof RedisQuery;
const testedFieldKeys: KeyType[] = ['keyName', 'query', 'field', 'filter', 'legend', 'value'];
testedFieldKeys.forEach((fieldKey) => {
describe(fieldKey, () => {
it('If value is exist should replace via templateSrv', () => {
const value = 'filter';
const query = getQuery({ [fieldKey]: value });
const scopedVars = { keyName: { value: 'key', key: '', text: '' } };
const resultQuery = dataSource.applyTemplateVariables(query, scopedVars);
expect(templateSrv.replace).toHaveBeenCalledWith(query[fieldKey], scopedVars);
expect(resultQuery).toEqual({
...query,
[fieldKey]: `replaced:${value}`,
});
});
it('If value is empty should not replace via templateSrv', () => {
const value = '';
const query = getQuery({ [fieldKey]: value });
const scopedVars = { keyName: { value: 'key', key: '', text: '' } };
const resultQuery = dataSource.applyTemplateVariables(query, scopedVars);
expect(templateSrv.replace).not.toHaveBeenCalled();
expect(resultQuery).toEqual({
...query,
[fieldKey]: value,
});
});
});
});
});

/**
* MetricFindQuery Method
*/
describe('metricFindQuery', () => {
it('If query is empty should return empty array', (done) => {
dataSource.metricFindQuery &&
dataSource.metricFindQuery('', { variable: { datasource: '123' } }).then((result: MetricFindValue[]) => {
expect(result).toEqual([]);
done();
});
});

it('If options.variables.datasource is empty should return empty array', (done) => {
dataSource.metricFindQuery &&
dataSource.metricFindQuery('123', { variable: { datasource: '' } }).then((result: MetricFindValue[]) => {
expect(result).toEqual([]);
done();
});
});

it('Should call query method', (done) => {
const querySpyMethod = jest.spyOn(dataSource, 'query').mockImplementation(
() =>
new Observable((subscriber) => {
subscriber.next({
data: [
{
fields: [
{
name: 'get',
values: {
toArray() {
return ['1', '2', '3'];
},
},
},
],
length: 1,
},
],
});
subscriber.complete();
})
);
dataSource.metricFindQuery &&
dataSource.metricFindQuery('123', { variable: { datasource: '123' } }).then((result: MetricFindValue[]) => {
expect(querySpyMethod).toHaveBeenCalled();
expect(result).toEqual([{ text: '1' }, { text: '2' }, { text: '3' }]);
done();
});
});
});

afterAll(() => {
superQueryMock.mockReset();
setTemplateSrv(null as any);
});
});
12 changes: 9 additions & 3 deletions src/module.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
describe('placeholder test', () => {
it('should return true', () => {
expect(true).toBeTruthy();
import { DataSourcePlugin } from '@grafana/data';
import { plugin } from './module';

/**
* Plugin
*/
describe('Plugin', () => {
it('Should be an instance of DataSourcePlugin', () => {
expect(plugin).toBeInstanceOf(DataSourcePlugin);
});
});
25 changes: 25 additions & 0 deletions src/tests/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { AggregationValue, InfoSectionValue, QueryTypeValue, RedisQuery } from '../redis';

/**
* Query
*/
export const getQuery = (overrideQuery: object = {}): RedisQuery => ({
keyName: '',
aggregation: AggregationValue.NONE,
bucket: 0,
legend: '',
command: '',
field: '',
filter: '',
value: '',
query: '',
type: QueryTypeValue.CLI,
section: InfoSectionValue.STATS,
size: 1,
fill: true,
streaming: true,
streamingInterval: 1,
streamingCapacity: 1,
refId: '',
...overrideQuery,
});