datasource.test.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { of, throwError } from 'rxjs';
  2. import { createFetchResponse } from 'test/helpers/createFetchResponse';
  3. import { backendSrv } from 'app/core/services/backend_srv';
  4. import { PostgresDatasource } from './datasource';
  5. jest.mock('@grafana/runtime', () => ({
  6. ...(jest.requireActual('@grafana/runtime') as any),
  7. getBackendSrv: () => backendSrv,
  8. getTemplateSrv: () => ({
  9. replace: (val: string): string => {
  10. return val;
  11. },
  12. }),
  13. }));
  14. describe('Postgres datasource', () => {
  15. beforeEach(() => {
  16. jest.clearAllMocks();
  17. });
  18. describe('when performing testDatasource call', () => {
  19. it('should return the error from the server', async () => {
  20. setupFetchMock(
  21. undefined,
  22. throwError(() => ({
  23. status: 400,
  24. statusText: 'Bad Request',
  25. data: {
  26. results: {
  27. meta: {
  28. error: 'db query error: pq: password authentication failed for user "postgres"',
  29. frames: [
  30. {
  31. schema: {
  32. refId: 'meta',
  33. meta: {
  34. executedQueryString: 'SELECT 1',
  35. },
  36. fields: [],
  37. },
  38. data: {
  39. values: [],
  40. },
  41. },
  42. ],
  43. },
  44. },
  45. },
  46. }))
  47. );
  48. const ds = new PostgresDatasource({ name: '', id: 0, jsonData: {} } as any);
  49. const result = await ds.testDatasource();
  50. expect(result.status).toEqual('error');
  51. expect(result.message).toEqual('db query error: pq: password authentication failed for user "postgres"');
  52. });
  53. });
  54. });
  55. function setupFetchMock(response: any, mock?: any) {
  56. const defaultMock = () => mock ?? of(createFetchResponse(response));
  57. const fetchMock = jest.spyOn(backendSrv, 'fetch');
  58. fetchMock.mockImplementation(defaultMock);
  59. return fetchMock;
  60. }