PlaylistNewPage.test.tsx 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { fireEvent, render, screen, waitFor } from '@testing-library/react';
  2. import userEvent from '@testing-library/user-event';
  3. import React from 'react';
  4. import { locationService } from '@grafana/runtime';
  5. import { backendSrv } from '../../core/services/backend_srv';
  6. import { PlaylistNewPage } from './PlaylistNewPage';
  7. import { Playlist } from './types';
  8. jest.mock('./usePlaylist', () => ({
  9. // so we don't need to add dashboard items in test
  10. usePlaylist: jest.fn().mockReturnValue({
  11. playlist: { items: [{ title: 'First item', type: 'dashboard_by_id', order: 1, value: '1' }], loading: false },
  12. }),
  13. }));
  14. jest.mock('@grafana/runtime', () => ({
  15. ...(jest.requireActual('@grafana/runtime') as any),
  16. getBackendSrv: () => backendSrv,
  17. }));
  18. jest.mock('../../core/components/TagFilter/TagFilter', () => ({
  19. TagFilter: () => {
  20. return <>mocked-tag-filter</>;
  21. },
  22. }));
  23. function getTestContext({ name, interval, items }: Partial<Playlist> = {}) {
  24. jest.clearAllMocks();
  25. const playlist = { name, items, interval } as unknown as Playlist;
  26. const queryParams = {};
  27. const route: any = {};
  28. const match: any = {};
  29. const location: any = {};
  30. const history: any = {};
  31. const navModel: any = {
  32. node: {},
  33. main: {},
  34. };
  35. const backendSrvMock = jest.spyOn(backendSrv, 'post');
  36. const { rerender } = render(
  37. <PlaylistNewPage
  38. queryParams={queryParams}
  39. route={route}
  40. match={match}
  41. location={location}
  42. history={history}
  43. navModel={navModel}
  44. />
  45. );
  46. return { playlist, rerender, backendSrvMock };
  47. }
  48. describe('PlaylistNewPage', () => {
  49. describe('when mounted', () => {
  50. it('then header should be correct', () => {
  51. getTestContext();
  52. expect(screen.getByRole('heading', { name: /new playlist/i })).toBeInTheDocument();
  53. });
  54. });
  55. describe('when submitted', () => {
  56. it('then correct api should be called', async () => {
  57. const { backendSrvMock } = getTestContext();
  58. expect(locationService.getLocation().pathname).toEqual('/');
  59. await userEvent.type(screen.getByRole('textbox', { name: /playlist name/i }), 'A Name');
  60. fireEvent.submit(screen.getByRole('button', { name: /save/i }));
  61. await waitFor(() => expect(backendSrvMock).toHaveBeenCalledTimes(1));
  62. expect(backendSrvMock).toHaveBeenCalledWith('/api/playlists', {
  63. name: 'A Name',
  64. interval: '5m',
  65. items: [{ title: 'First item', type: 'dashboard_by_id', order: 1, value: '1' }],
  66. });
  67. expect(locationService.getLocation().pathname).toEqual('/playlists');
  68. });
  69. });
  70. });