utils.test.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import store from '../../../core/store';
  2. import { lastUsedDatasourceKeyForOrgId } from '../../../core/utils/explore';
  3. const dataSourceMock = {
  4. get: jest.fn(),
  5. };
  6. jest.mock('app/features/plugins/datasource_srv', () => ({
  7. getDatasourceSrv: jest.fn(() => dataSourceMock),
  8. }));
  9. jest.spyOn(store, 'set');
  10. import { loadAndInitDatasource } from './utils';
  11. const DEFAULT_DATASOURCE = { uid: 'abc123', name: 'Default' };
  12. const TEST_DATASOURCE = { uid: 'def789', name: 'Test' };
  13. describe('loadAndInitDatasource', () => {
  14. beforeEach(() => {
  15. jest.clearAllMocks();
  16. });
  17. it('falls back to default datasource if the provided one was not found', async () => {
  18. dataSourceMock.get.mockRejectedValueOnce(new Error('Datasource not found'));
  19. dataSourceMock.get.mockResolvedValue(DEFAULT_DATASOURCE);
  20. const { instance } = await loadAndInitDatasource(1, 'Unknown');
  21. expect(dataSourceMock.get).toBeCalledTimes(2);
  22. expect(dataSourceMock.get).toBeCalledWith('Unknown');
  23. expect(dataSourceMock.get).toBeCalledWith();
  24. expect(instance).toMatchObject(DEFAULT_DATASOURCE);
  25. expect(store.set).toBeCalledWith(lastUsedDatasourceKeyForOrgId(1), DEFAULT_DATASOURCE.uid);
  26. });
  27. it('saves last loaded data source uid', async () => {
  28. dataSourceMock.get.mockResolvedValue(TEST_DATASOURCE);
  29. const { instance } = await loadAndInitDatasource(1, 'Test');
  30. expect(dataSourceMock.get).toBeCalledTimes(1);
  31. expect(dataSourceMock.get).toBeCalledWith('Test');
  32. expect(instance).toMatchObject(TEST_DATASOURCE);
  33. expect(store.set).toBeCalledWith(lastUsedDatasourceKeyForOrgId(1), TEST_DATASOURCE.uid);
  34. });
  35. });