1import { variableQueryObserver } from './variableQueryObserver';
2import { LoadingState } from '@grafana/data';
3import { VariableIdentifier } from '../state/types';
4import { UpdateOptionsResults } from './VariableQueryRunner';
5
6function getTestContext(args: { next?: UpdateOptionsResults; error?: any; complete?: boolean }) {
7  const { next, error, complete } = args;
8  const resolve = jest.fn();
9  const reject = jest.fn();
10  const subscription: any = {
11    unsubscribe: jest.fn(),
12  };
13  const observer = variableQueryObserver(resolve, reject, subscription);
14
15  if (next) {
16    observer.next(next);
17  }
18
19  if (error) {
20    observer.error(error);
21  }
22
23  if (complete) {
24    observer.complete();
25  }
26
27  return { resolve, reject, subscription, observer };
28}
29
30const identifier: VariableIdentifier = { id: 'id', type: 'query' };
31
32describe('variableQueryObserver', () => {
33  describe('when receiving a Done state', () => {
34    it('then it should call unsubscribe', () => {
35      const { subscription } = getTestContext({ next: { state: LoadingState.Done, identifier } });
36
37      expect(subscription.unsubscribe).toHaveBeenCalledTimes(1);
38    });
39
40    it('then it should call resolve', () => {
41      const { resolve } = getTestContext({ next: { state: LoadingState.Done, identifier } });
42
43      expect(resolve).toHaveBeenCalledTimes(1);
44    });
45  });
46
47  describe('when receiving an Error state', () => {
48    it('then it should call unsubscribe', () => {
49      const { subscription } = getTestContext({ next: { state: LoadingState.Error, identifier, error: 'An error' } });
50
51      expect(subscription.unsubscribe).toHaveBeenCalledTimes(1);
52    });
53
54    it('then it should call reject', () => {
55      const { reject } = getTestContext({ next: { state: LoadingState.Error, identifier, error: 'An error' } });
56
57      expect(reject).toHaveBeenCalledTimes(1);
58      expect(reject).toHaveBeenCalledWith('An error');
59    });
60  });
61
62  describe('when receiving an error', () => {
63    it('then it should call unsubscribe', () => {
64      const { subscription } = getTestContext({ error: 'An error' });
65
66      expect(subscription.unsubscribe).toHaveBeenCalledTimes(1);
67    });
68
69    it('then it should call reject', () => {
70      const { reject } = getTestContext({ error: 'An error' });
71
72      expect(reject).toHaveBeenCalledTimes(1);
73      expect(reject).toHaveBeenCalledWith('An error');
74    });
75  });
76
77  describe('when receiving complete', () => {
78    it('then it should call unsubscribe', () => {
79      const { subscription } = getTestContext({ complete: true });
80
81      expect(subscription.unsubscribe).toHaveBeenCalledTimes(1);
82    });
83
84    it('then it should call resolve', () => {
85      const { resolve } = getTestContext({ complete: true });
86
87      expect(resolve).toHaveBeenCalledTimes(1);
88    });
89  });
90});
91