actions.test.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { Observable, of, throwError } from 'rxjs';
  2. import { thunkTester } from 'test/core/thunk/thunkTester';
  3. import { FetchResponse } from '@grafana/runtime';
  4. import { notifyApp } from 'app/core/actions';
  5. import { createWarningNotification } from 'app/core/copy/appNotification';
  6. import { backendSrv } from 'app/core/services/backend_srv';
  7. import { checkFolderPermissions } from './actions';
  8. import { setCanViewFolderPermissions } from './reducers';
  9. describe('folder actions', () => {
  10. let fetchSpy: jest.SpyInstance<Observable<FetchResponse<unknown>>>;
  11. beforeAll(() => {
  12. fetchSpy = jest.spyOn(backendSrv, 'fetch');
  13. });
  14. afterAll(() => {
  15. fetchSpy.mockRestore();
  16. });
  17. function mockFetch(resp: Observable<any>) {
  18. fetchSpy.mockReturnValueOnce(resp);
  19. }
  20. const folderUid = 'abc123';
  21. describe('checkFolderPermissions', () => {
  22. it('should dispatch true when the api call is successful', async () => {
  23. mockFetch(of({}));
  24. const dispatchedActions = await thunkTester({})
  25. .givenThunk(checkFolderPermissions)
  26. .whenThunkIsDispatched(folderUid);
  27. expect(dispatchedActions).toEqual([setCanViewFolderPermissions(true)]);
  28. });
  29. it('should dispatch just "false" when the api call fails with 403', async () => {
  30. mockFetch(throwError(() => ({ status: 403, data: { message: 'Access denied' } })));
  31. const dispatchedActions = await thunkTester({})
  32. .givenThunk(checkFolderPermissions)
  33. .whenThunkIsDispatched(folderUid);
  34. expect(dispatchedActions).toEqual([setCanViewFolderPermissions(false)]);
  35. });
  36. it('should also dispatch a notification when the api call fails with an error other than 403', async () => {
  37. mockFetch(throwError(() => ({ status: 500, data: { message: 'Server error' } })));
  38. const dispatchedActions = await thunkTester({})
  39. .givenThunk(checkFolderPermissions)
  40. .whenThunkIsDispatched(folderUid);
  41. const notificationAction = notifyApp(
  42. createWarningNotification('Error checking folder permissions', 'Server error')
  43. );
  44. notificationAction.payload.id = expect.any(String);
  45. notificationAction.payload.timestamp = expect.any(Number);
  46. expect(dispatchedActions).toEqual([
  47. expect.objectContaining(notificationAction),
  48. setCanViewFolderPermissions(false),
  49. ]);
  50. });
  51. });
  52. });