OrgSwitcher.test.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { render, screen, waitFor, within } from '@testing-library/react';
  2. import userEvent from '@testing-library/user-event';
  3. import React from 'react';
  4. import { api } from '../../features/profile/api';
  5. import { OrgRole } from '../../types';
  6. import { OrgSwitcher } from '../components/OrgSwitcher';
  7. jest.mock('@grafana/runtime', () => ({
  8. config: {
  9. appSubUrl: '/subUrl',
  10. },
  11. }));
  12. jest.mock('app/core/services/context_srv', () => ({
  13. contextSrv: {
  14. user: { orgId: 1 },
  15. },
  16. }));
  17. describe('OrgSwitcher', () => {
  18. const { location } = window;
  19. let setUserOrgSpy: jest.SpyInstance;
  20. beforeEach(async () => {
  21. jest.clearAllMocks();
  22. const orgs = [
  23. { orgId: 1, name: 'Main Org.', role: OrgRole.Admin },
  24. { orgId: 2, name: 'Org 2', role: OrgRole.Admin },
  25. ];
  26. const loadOrgsSpy = jest.spyOn(api, 'loadOrgs').mockResolvedValue(orgs);
  27. setUserOrgSpy = jest.spyOn(api, 'setUserOrg').mockResolvedValue(undefined);
  28. // @ts-ignore
  29. delete window.location;
  30. window.location = {} as Location;
  31. render(<OrgSwitcher onDismiss={() => {}} />);
  32. await waitFor(() => expect(loadOrgsSpy).toHaveBeenCalledTimes(1));
  33. });
  34. afterEach(() => {
  35. window.location = location;
  36. });
  37. describe('when switching org', () => {
  38. it('should render correct rows', async () => {
  39. expect(screen.getAllByRole('row')).toHaveLength(3); // header + 2 orgs
  40. expect(screen.getByRole('row', { name: /main org. admin current/i })).toBeInTheDocument();
  41. expect(screen.getByRole('row', { name: /org 2 admin switch to/i })).toBeInTheDocument();
  42. });
  43. it('should switch orgId in call to backend', async () => {
  44. const row = screen.getByRole('row', { name: /org 2 admin switch to/i });
  45. const switchToButton = within(row).getByText(/switch to/i);
  46. await userEvent.click(switchToButton);
  47. await waitFor(() => expect(setUserOrgSpy).toBeCalledWith({ orgId: 2, name: 'Org 2', role: 'Admin' }));
  48. });
  49. it('should redirect to home page', async () => {
  50. expect(window.location.href).toBeUndefined();
  51. const row = screen.getByRole('row', { name: /org 2 admin switch to/i });
  52. const switchToButton = within(row).getByText(/switch to/i);
  53. await userEvent.click(switchToButton);
  54. await waitFor(() => expect(window.location.href).toEqual('/subUrl/?orgId=2'));
  55. });
  56. });
  57. });