-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathElasticsearchQueryContext.test.tsx
76 lines (63 loc) · 2.41 KB
/
ElasticsearchQueryContext.test.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { render } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import React, { PropsWithChildren } from 'react';
import { CoreApp, getDefaultTimeRange } from '@grafana/data';
import { ElasticDatasource } from '@/datasource';
import { ElasticsearchQuery } from '@/types';
import { ElasticsearchProvider, useQuery } from './ElasticsearchQueryContext';
const query: ElasticsearchQuery = {
refId: 'A',
query: '',
metrics: [{ id: '1', type: 'count' }],
bucketAggs: [{ type: 'date_histogram', id: '2' }],
};
describe('ElasticsearchQueryContext', () => {
it('Should call onChange and onRunQuery with the default query when the query is empty', () => {
const datasource = { timeField: 'TIMEFIELD' } as ElasticDatasource;
const onChange = jest.fn();
const onRunQuery = jest.fn();
render(
<ElasticsearchProvider
query={{ refId: 'A' }}
app={CoreApp.Unknown}
onChange={onChange}
datasource={datasource}
onRunQuery={onRunQuery}
range={getDefaultTimeRange()}
/>
);
const changedQuery: ElasticsearchQuery = onChange.mock.calls[0][0];
expect(changedQuery.query).toBeDefined();
expect(changedQuery.alias).toBeDefined();
expect(changedQuery.metrics).toBeDefined();
expect(changedQuery.bucketAggs).toBeDefined();
// Should also set timeField to the configured `timeField` option in datasource configuration
expect(changedQuery.timeField).toBe(datasource.timeField);
expect(onRunQuery).toHaveBeenCalled();
});
// the following applies to all hooks in ElasticsearchQueryContext as they all share the same code.
describe('useQuery Hook', () => {
it('Should throw when used outside of ElasticsearchQueryContext', () => {
const { result } = renderHook(() => useQuery());
expect(result.error).toBeTruthy();
});
it('Should return the current query object', () => {
const wrapper = ({ children }: PropsWithChildren<{}>) => (
<ElasticsearchProvider
datasource={{} as ElasticDatasource}
query={query}
app={CoreApp.Unknown}
onChange={() => {}}
onRunQuery={() => {}}
range={getDefaultTimeRange()}
>
{children}
</ElasticsearchProvider>
);
const { result } = renderHook(() => useQuery(), {
wrapper,
});
expect(result.current).toBe(query);
});
});
});