prometheus

Форк
0
314 строк · 9.5 Кб
1
import * as React from 'react';
2
import $ from 'jquery';
3
import { shallow, mount } from 'enzyme';
4
import Graph from './Graph';
5
import ReactResizeDetector from 'react-resize-detector';
6
import { Legend } from './Legend';
7
import { GraphDisplayMode } from './Panel';
8

9
describe('Graph', () => {
10
  beforeAll(() => {
11
    jest.spyOn(window, 'requestAnimationFrame').mockImplementation((cb: any) => cb());
12
  });
13

14
  // Source: https://github.com/maslianok/react-resize-detector#testing-with-enzyme-and-jest
15
  beforeEach(() => {
16
    window.ResizeObserver = jest.fn().mockImplementation(() => ({
17
      observe: jest.fn(),
18
      unobserve: jest.fn(),
19
      disconnect: jest.fn(),
20
    }));
21
  });
22

23
  afterEach(() => {
24
    window.ResizeObserver = ResizeObserver;
25
  });
26

27
  describe('data is returned', () => {
28
    const props: any = {
29
      queryParams: {
30
        startTime: 1572128592,
31
        endTime: 1572130692,
32
        resolution: 28,
33
      },
34
      displayMode: GraphDisplayMode.Stacked,
35
      data: {
36
        resultType: 'matrix',
37
        result: [
38
          {
39
            metric: {
40
              code: '200',
41
              handler: '/graph',
42
              instance: 'localhost:9090',
43
              job: 'prometheus',
44
            },
45
            values: [
46
              [1572128592, '23'],
47
              [1572128620, '2'],
48
              [1572128648, '4'],
49
              [1572128676, '1'],
50
              [1572128704, '2'],
51
              [1572128732, '12'],
52
              [1572128760, '1'],
53
              [1572128788, '0'],
54
              [1572128816, '0'],
55
              [1572128844, '2'],
56
              [1572128872, '5'],
57
              [1572130384, '6'],
58
              [1572130412, '7'],
59
              [1572130440, '19'],
60
              [1572130468, '33'],
61
              [1572130496, '14'],
62
              [1572130524, '7'],
63
              [1572130552, '6'],
64
              [1572130580, '0'],
65
              [1572130608, '0'],
66
              [1572130636, '0'],
67
              [1572130664, '0'],
68
              [1572130692, '0'],
69
            ],
70
          },
71
        ],
72
        exemplars: [
73
          {
74
            seriesLabels: {
75
              code: '200',
76
              handler: '/graph',
77
              instance: 'localhost:9090',
78
              job: 'prometheus',
79
            },
80
            exemplars: [
81
              {
82
                labels: {
83
                  trace_id: '12345',
84
                },
85
                timestamp: 1572130580,
86
                value: '9',
87
              },
88
            ],
89
          },
90
        ],
91
      },
92
      id: 'test',
93
    };
94
    it('renders a graph with props', () => {
95
      const graph = shallow(<Graph {...props} />);
96
      const div = graph.find('div').filterWhere((elem) => elem.prop('className') === 'graph-test');
97
      const resize = div.find(ReactResizeDetector);
98
      const innerdiv = div.find('div').filterWhere((elem) => elem.prop('className') === 'graph-chart');
99
      expect(resize.prop('handleWidth')).toBe(true);
100
      expect(div).toHaveLength(1);
101
      expect(innerdiv).toHaveLength(1);
102
    });
103
    describe('Legend', () => {
104
      it('renders a legend', () => {
105
        const graph = shallow(<Graph {...props} />);
106
        expect(graph.find(Legend)).toHaveLength(1);
107
      });
108
    });
109
  });
110
  describe('on component update', () => {
111
    let graph: any;
112
    let spyState: any;
113
    let mockPlot: any;
114
    beforeEach(() => {
115
      mockPlot = jest.spyOn($, 'plot').mockReturnValue({ setData: jest.fn(), draw: jest.fn(), destroy: jest.fn() } as any);
116
      graph = mount(
117
        <Graph
118
          {...({
119
            displayMode: GraphDisplayMode.Stacked,
120
            queryParams: {
121
              startTime: 1572128592,
122
              endTime: 1572128598,
123
              resolution: 28,
124
            },
125
            data: { result: [{ values: [], metric: {} }] },
126
          } as any)}
127
        />
128
      );
129
      spyState = jest.spyOn(graph.instance(), 'setState');
130
    });
131
    afterEach(() => {
132
      spyState.mockReset();
133
      mockPlot.mockReset();
134
    });
135
    it('should trigger state update when new data is received', () => {
136
      graph.setProps({ data: { result: [{ values: [{}], metric: {} }] } });
137
      expect(spyState).toHaveBeenCalledWith(
138
        {
139
          chartData: {
140
            exemplars: [],
141
            series: [
142
              {
143
                color: '#008000',
144
                data: [[1572128592000, null]],
145
                index: 0,
146
                labels: {},
147
                stack: true,
148
              },
149
            ],
150
          },
151
        },
152
        expect.anything()
153
      );
154
    });
155
    it('should trigger state update when stacked prop is changed', () => {
156
      graph.setProps({ displayMode: GraphDisplayMode.Lines });
157
      expect(spyState).toHaveBeenCalledWith(
158
        {
159
          chartData: {
160
            exemplars: [],
161
            series: [
162
              {
163
                color: '#008000',
164
                data: [[1572128592000, null]],
165
                index: 0,
166
                labels: {},
167
                stack: false,
168
              },
169
            ],
170
          },
171
        },
172
        expect.anything()
173
      );
174
    });
175
  });
176
  describe('on unmount', () => {
177
    it('should call destroy plot', () => {
178
      const graph = mount(
179
        <Graph
180
          {...({
181
            displayMode: GraphDisplayMode.Stacked,
182
            queryParams: {
183
              startTime: 1572128592,
184
              endTime: 1572130692,
185
              resolution: 28,
186
            },
187
            data: { result: [{ values: [], metric: {} }] },
188
          } as any)}
189
        />
190
      );
191
      const spyPlotDestroy = jest.spyOn(graph.instance(), 'componentWillUnmount');
192
      graph.unmount();
193
      expect(spyPlotDestroy).toHaveBeenCalledTimes(1);
194
      spyPlotDestroy.mockReset();
195
    });
196
  });
197

198
  describe('plot', () => {
199
    it('should not call jquery.plot if chartRef not exist', () => {
200
      const mockSetData = jest.fn();
201
      jest.spyOn($, 'plot').mockReturnValue({ setData: mockSetData, draw: jest.fn(), destroy: jest.fn() } as any);
202
      const graph = shallow(
203
        <Graph
204
          {...({
205
            displayMode: GraphDisplayMode.Stacked,
206
            queryParams: {
207
              startTime: 1572128592,
208
              endTime: 1572128598,
209
              resolution: 28,
210
            },
211
            data: { result: [{ values: [], metric: {} }] },
212
          } as any)}
213
        />
214
      );
215
      (graph.instance() as any).plot();
216
      expect(mockSetData).not.toBeCalled();
217
    });
218
    it('should call jquery.plot if chartRef exist', () => {
219
      const mockPlot = jest
220
        .spyOn($, 'plot')
221
        .mockReturnValue({ setData: jest.fn(), draw: jest.fn(), destroy: jest.fn() } as any);
222
      const graph = mount(
223
        <Graph
224
          {...({
225
            displayMode: GraphDisplayMode.Stacked,
226
            queryParams: {
227
              startTime: 1572128592,
228
              endTime: 1572128598,
229
              resolution: 28,
230
            },
231
            data: { result: [{ values: [], metric: {} }] },
232
          } as any)}
233
        />
234
      );
235
      (graph.instance() as any).plot();
236
      expect(mockPlot).toBeCalled();
237
    });
238
    it('should destroy plot', () => {
239
      const mockDestroy = jest.fn();
240
      jest.spyOn($, 'plot').mockReturnValue({ setData: jest.fn(), draw: jest.fn(), destroy: mockDestroy } as any);
241
      const graph = mount(
242
        <Graph
243
          {...({
244
            displayMode: GraphDisplayMode.Stacked,
245
            queryParams: {
246
              startTime: 1572128592,
247
              endTime: 1572128598,
248
              resolution: 28,
249
            },
250
            data: { result: [{ values: [], metric: {} }] },
251
          } as any)}
252
        />
253
      );
254
      (graph.instance() as any).plot();
255
      (graph.instance() as any).destroyPlot();
256
      expect(mockDestroy).toHaveBeenCalledTimes(2);
257
    });
258
  });
259
  describe('plotSetAndDraw', () => {
260
    it('should call spyPlotSetAndDraw on legend hover', () => {
261
      jest.spyOn($, 'plot').mockReturnValue({ setData: jest.fn(), draw: jest.fn(), destroy: jest.fn() } as any);
262
      const graph = mount(
263
        <Graph
264
          {...({
265
            displayMode: GraphDisplayMode.Stacked,
266
            queryParams: {
267
              startTime: 1572128592,
268
              endTime: 1572128598,
269
              resolution: 28,
270
            },
271
            data: {
272
              result: [
273
                { values: [], metric: {} },
274
                { values: [], metric: {} },
275
              ],
276
            },
277
          } as any)}
278
        />
279
      );
280
      (graph.instance() as any).plot(); // create chart
281
      const spyPlotSetAndDraw = jest.spyOn(graph.instance() as any, 'plotSetAndDraw');
282
      graph.find('.legend-item').at(0).simulate('mouseover');
283
      expect(spyPlotSetAndDraw).toHaveBeenCalledTimes(1);
284
    });
285
    it('should call spyPlotSetAndDraw with chartDate from state as default value', () => {
286
      const mockSetData = jest.fn();
287
      const spyPlot = jest
288
        .spyOn($, 'plot')
289
        .mockReturnValue({ setData: mockSetData, draw: jest.fn(), destroy: jest.fn() } as any);
290
      const graph: any = mount(
291
        <Graph
292
          {...({
293
            displayMode: GraphDisplayMode.Stacked,
294
            queryParams: {
295
              startTime: 1572128592,
296
              endTime: 1572128598,
297
              resolution: 28,
298
            },
299
            data: {
300
              result: [
301
                { values: [], metric: {} },
302
                { values: [], metric: {} },
303
              ],
304
            },
305
          } as any)}
306
        />
307
      );
308
      (graph.instance() as any).plot(); // create chart
309
      graph.find('.graph-legend').simulate('mouseout');
310
      expect(mockSetData).toHaveBeenCalledWith(graph.state().chartData.series);
311
      spyPlot.mockReset();
312
    });
313
  });
314
});
315

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.