index.spec.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import type {ComponentProps} from 'react';
  2. import styled from '@emotion/styled';
  3. import {OrganizationFixture} from 'sentry-fixture/organization';
  4. import {TeamFixture} from 'sentry-fixture/team';
  5. import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
  6. import selectEvent from 'sentry-test/selectEvent';
  7. import {textWithMarkupMatcher} from 'sentry-test/utils';
  8. import {makeCloseButton} from 'sentry/components/globalModal/components';
  9. import InviteMembersModal from 'sentry/components/modals/inviteMembersModal';
  10. import {ORG_ROLES} from 'sentry/constants';
  11. import TeamStore from 'sentry/stores/teamStore';
  12. import type {DetailedTeam, Scope} from 'sentry/types';
  13. import useOrganization from 'sentry/utils/useOrganization';
  14. jest.mock('sentry/utils/useOrganization');
  15. describe('InviteMembersModal', function () {
  16. const styledWrapper = styled(c => c.children);
  17. type MockApiResponseFn = (
  18. client: typeof MockApiClient,
  19. orgSlug: string,
  20. roles?: object[]
  21. ) => jest.Mock;
  22. const defaultMockOrganizationRoles: MockApiResponseFn = (client, orgSlug, roles) => {
  23. return client.addMockResponse({
  24. url: `/organizations/${orgSlug}/members/me/`,
  25. method: 'GET',
  26. body: {roles},
  27. });
  28. };
  29. const defaultMockPostOrganizationMember: MockApiResponseFn = (client, orgSlug, _) => {
  30. return client.addMockResponse({
  31. url: `/organizations/${orgSlug}/members/`,
  32. method: 'POST',
  33. });
  34. };
  35. const defaultMockModalProps = {
  36. Body: styledWrapper(),
  37. Header: p => <span>{p.children}</span>,
  38. Footer: styledWrapper(),
  39. closeModal: () => {},
  40. CloseButton: makeCloseButton(() => {}),
  41. };
  42. const setupView = ({
  43. orgTeams = [TeamFixture()],
  44. orgAccess = ['member:write'],
  45. roles = [
  46. {
  47. id: 'admin',
  48. name: 'Admin',
  49. desc: 'This is the admin role',
  50. allowed: true,
  51. },
  52. {
  53. id: 'member',
  54. name: 'Member',
  55. desc: 'This is the member role',
  56. allowed: true,
  57. },
  58. ],
  59. modalProps = defaultMockModalProps,
  60. mockApiResponses = [defaultMockOrganizationRoles],
  61. }: {
  62. mockApiResponses?: MockApiResponseFn[];
  63. modalProps?: ComponentProps<typeof InviteMembersModal>;
  64. orgAccess?: Scope[];
  65. orgTeams?: DetailedTeam[];
  66. roles?: object[];
  67. } = {}) => {
  68. const org = OrganizationFixture({access: orgAccess, teams: orgTeams});
  69. TeamStore.reset();
  70. TeamStore.loadInitialData(orgTeams);
  71. MockApiClient.clearMockResponses();
  72. const mocks: jest.Mock[] = [];
  73. mockApiResponses.forEach(mockApiResponse => {
  74. mocks.push(mockApiResponse(MockApiClient, org.slug, roles));
  75. });
  76. jest.mocked(useOrganization).mockReturnValue(org);
  77. return {...render(<InviteMembersModal {...modalProps} />), mocks};
  78. };
  79. const setupMemberInviteState = async () => {
  80. // Setup two rows, one email each, the first with a admin role.
  81. await userEvent.click(screen.getByRole('button', {name: 'Add another'}));
  82. const emailInputs = screen.getAllByRole('textbox', {name: 'Email Addresses'});
  83. const roleInputs = screen.getAllByRole('textbox', {name: 'Role'});
  84. await userEvent.type(emailInputs[0], 'test1@test.com');
  85. await userEvent.tab();
  86. await selectEvent.select(roleInputs[0], 'Admin');
  87. await userEvent.type(emailInputs[1], 'test2@test.com');
  88. await userEvent.tab();
  89. };
  90. it('renders', async function () {
  91. setupView();
  92. await waitFor(() => {
  93. // Starts with one invite row
  94. expect(screen.getByRole('listitem')).toBeInTheDocument();
  95. });
  96. // We have two roles loaded from the members/me endpoint, defaulting to the
  97. // 'member' role.
  98. await userEvent.click(screen.getByRole('textbox', {name: 'Role'}));
  99. expect(screen.getAllByRole('menuitemradio')).toHaveLength(2);
  100. expect(screen.getByRole('menuitemradio', {name: 'Member'})).toBeChecked();
  101. });
  102. it('renders for superuser', async function () {
  103. jest.mock('sentry/utils/isActiveSuperuser', () => ({
  104. isActiveSuperuser: jest.fn(),
  105. }));
  106. const errorResponse: MockApiResponseFn = (client, orgSlug, _) => {
  107. return client.addMockResponse({
  108. url: `/organizations/${orgSlug}/members/me/`,
  109. method: 'GET',
  110. status: 404,
  111. });
  112. };
  113. setupView({mockApiResponses: [errorResponse]});
  114. expect(await screen.findByRole('listitem')).toBeInTheDocument();
  115. await userEvent.click(screen.getByRole('textbox', {name: 'Role'}));
  116. expect(screen.getAllByRole('menuitemradio')).toHaveLength(ORG_ROLES.length);
  117. expect(screen.getByRole('menuitemradio', {name: 'Member'})).toBeChecked();
  118. });
  119. it('renders without organization.access', async function () {
  120. setupView({orgAccess: undefined});
  121. expect(await screen.findByRole('listitem')).toBeInTheDocument();
  122. });
  123. it('can add a second row', async function () {
  124. setupView();
  125. expect(await screen.findByRole('listitem')).toBeInTheDocument();
  126. await userEvent.click(screen.getByRole('button', {name: 'Add another'}));
  127. expect(screen.getAllByRole('listitem')).toHaveLength(2);
  128. });
  129. it('errors on duplicate emails', async function () {
  130. setupView();
  131. expect(await screen.findByRole('button', {name: 'Add another'})).toBeInTheDocument();
  132. await userEvent.click(screen.getByRole('button', {name: 'Add another'}));
  133. const emailInputs = screen.getAllByRole('textbox', {name: 'Email Addresses'});
  134. await userEvent.type(emailInputs[0], 'test@test.com');
  135. await userEvent.tab();
  136. await userEvent.type(emailInputs[1], 'test@test.com');
  137. await userEvent.tab();
  138. expect(screen.getByText('Duplicate emails between invite rows.')).toBeInTheDocument();
  139. });
  140. it('indicates the total invites on the invite button', async function () {
  141. setupView();
  142. expect(
  143. await screen.findByRole('textbox', {name: 'Email Addresses'})
  144. ).toBeInTheDocument();
  145. const emailInput = screen.getByRole('textbox', {name: 'Email Addresses'});
  146. await userEvent.type(emailInput, 'test@test.com');
  147. await userEvent.tab();
  148. await userEvent.type(emailInput, 'test2@test.com');
  149. await userEvent.tab();
  150. expect(screen.getByRole('button', {name: 'Send invites (2)'})).toBeInTheDocument();
  151. });
  152. it('can be closed', async function () {
  153. const close = jest.fn();
  154. const modalProps = {
  155. ...defaultMockModalProps,
  156. closeModal: close,
  157. };
  158. setupView({modalProps});
  159. expect(await screen.findByRole('button', {name: 'Cancel'})).toBeInTheDocument();
  160. await userEvent.click(screen.getByRole('button', {name: 'Cancel'}));
  161. expect(close).toHaveBeenCalled();
  162. });
  163. it('sends all successful invites without team defaults', async function () {
  164. const {mocks} = setupView({
  165. mockApiResponses: [defaultMockOrganizationRoles, defaultMockPostOrganizationMember],
  166. });
  167. expect(await screen.findByRole('button', {name: 'Add another'})).toBeInTheDocument();
  168. await setupMemberInviteState();
  169. const teamInputs = screen.getAllByRole('textbox', {name: 'Add to Team'});
  170. await selectEvent.select(teamInputs[0], '#team-slug');
  171. await selectEvent.select(teamInputs[1], '#team-slug');
  172. await userEvent.click(screen.getByRole('button', {name: 'Send invites (2)'}));
  173. // Verify data sent to the backend
  174. const mockPostApi = mocks[1];
  175. expect(mockPostApi).toHaveBeenCalledTimes(2);
  176. expect(mockPostApi).toHaveBeenNthCalledWith(
  177. 1,
  178. `/organizations/org-slug/members/`,
  179. expect.objectContaining({
  180. data: {email: 'test1@test.com', role: 'admin', teams: []},
  181. })
  182. );
  183. expect(mockPostApi).toHaveBeenNthCalledWith(
  184. 2,
  185. `/organizations/org-slug/members/`,
  186. expect.objectContaining({
  187. data: {email: 'test2@test.com', role: 'member', teams: []},
  188. })
  189. );
  190. });
  191. it('can reset modal', async function () {
  192. setupView({
  193. mockApiResponses: [defaultMockOrganizationRoles, defaultMockPostOrganizationMember],
  194. });
  195. expect(await screen.findByRole('button', {name: 'Add another'})).toBeInTheDocument();
  196. await setupMemberInviteState();
  197. await userEvent.click(screen.getByRole('button', {name: 'Send invites (2)'}));
  198. // Wait for them to finish
  199. expect(
  200. await screen.findByText(textWithMarkupMatcher('Sent 2 invites'))
  201. ).toBeInTheDocument();
  202. // Reset the modal
  203. await userEvent.click(screen.getByRole('button', {name: 'Send more invites'}));
  204. expect(screen.getByRole('button', {name: 'Send invite'})).toBeDisabled();
  205. });
  206. it('sends all successful invites with team default', async function () {
  207. const {mocks} = setupView({
  208. mockApiResponses: [defaultMockOrganizationRoles, defaultMockPostOrganizationMember],
  209. });
  210. expect(await screen.findByRole('button', {name: 'Add another'})).toBeInTheDocument();
  211. await setupMemberInviteState();
  212. await userEvent.click(screen.getByRole('button', {name: 'Send invites (2)'}));
  213. const mockPostApi = mocks[1];
  214. expect(mockPostApi).toHaveBeenCalledTimes(2);
  215. expect(mockPostApi).toHaveBeenNthCalledWith(
  216. 1,
  217. `/organizations/org-slug/members/`,
  218. expect.objectContaining({
  219. data: {email: 'test1@test.com', role: 'admin', teams: ['team-slug']},
  220. })
  221. );
  222. expect(mockPostApi).toHaveBeenNthCalledWith(
  223. 2,
  224. `/organizations/org-slug/members/`,
  225. expect.objectContaining({
  226. data: {email: 'test2@test.com', role: 'member', teams: ['team-slug']},
  227. })
  228. );
  229. });
  230. it('does not use defaults when there are multiple teams', async function () {
  231. const another_team = TeamFixture({id: '2', slug: 'team2'});
  232. setupView({orgTeams: [TeamFixture(), another_team]});
  233. expect(await screen.findByRole('button', {name: 'Add another'})).toBeInTheDocument();
  234. await userEvent.click(screen.getByRole('button', {name: 'Add another'}));
  235. const teamInputs = screen.getAllByRole('textbox', {name: 'Add to Team'});
  236. expect(teamInputs).toHaveLength(2);
  237. expect(teamInputs[0]).toHaveValue('');
  238. expect(teamInputs[1]).toHaveValue('');
  239. });
  240. it('marks failed invites', async function () {
  241. const failedCreateMemberMock = (client, orgSlug, _) => {
  242. return client.addMockResponse({
  243. url: `/organizations/${orgSlug}/members/`,
  244. method: 'POST',
  245. statusCode: 400,
  246. });
  247. };
  248. const {mocks} = setupView({
  249. mockApiResponses: [defaultMockOrganizationRoles, failedCreateMemberMock],
  250. });
  251. expect(
  252. await screen.findByRole('textbox', {name: 'Email Addresses'})
  253. ).toBeInTheDocument();
  254. await userEvent.type(
  255. screen.getByRole('textbox', {name: 'Email Addresses'}),
  256. 'bademail'
  257. );
  258. await userEvent.tab();
  259. await userEvent.click(screen.getByRole('button', {name: 'Send invite'}));
  260. const failedApiMock = mocks[1];
  261. expect(failedApiMock).toHaveBeenCalled();
  262. expect(
  263. await screen.findByText(textWithMarkupMatcher('Sent 0 invites, 1 failed to send.'))
  264. ).toBeInTheDocument();
  265. });
  266. it('can send initial email', async function () {
  267. const initialEmail = 'test@gmail.com';
  268. const initialData = [{emails: new Set([initialEmail])}];
  269. const {mocks} = setupView({
  270. mockApiResponses: [defaultMockOrganizationRoles, defaultMockPostOrganizationMember],
  271. modalProps: {
  272. ...defaultMockModalProps,
  273. initialData,
  274. },
  275. });
  276. await waitFor(() => {
  277. expect(screen.getByText(initialEmail)).toBeInTheDocument();
  278. });
  279. // Just immediately click send
  280. await userEvent.click(screen.getByRole('button', {name: 'Send invite'}));
  281. const apiMock = mocks[1];
  282. expect(apiMock).toHaveBeenCalledWith(
  283. `/organizations/org-slug/members/`,
  284. expect.objectContaining({
  285. data: {email: initialEmail, role: 'member', teams: ['team-slug']},
  286. })
  287. );
  288. expect(
  289. await screen.findByText(textWithMarkupMatcher('Sent 1 invite'))
  290. ).toBeInTheDocument();
  291. });
  292. it('can send initial email with role and team', async function () {
  293. const initialEmail = 'test@gmail.com';
  294. const role = 'admin';
  295. const initialData = [
  296. {emails: new Set([initialEmail]), role, teams: new Set([TeamFixture().slug])},
  297. ];
  298. const {mocks} = setupView({
  299. mockApiResponses: [defaultMockOrganizationRoles, defaultMockPostOrganizationMember],
  300. modalProps: {
  301. ...defaultMockModalProps,
  302. initialData,
  303. },
  304. });
  305. expect(await screen.findByRole('button', {name: 'Send invite'})).toBeInTheDocument();
  306. // Just immediately click send
  307. await userEvent.click(screen.getByRole('button', {name: 'Send invite'}));
  308. expect(screen.getByText(initialEmail)).toBeInTheDocument();
  309. expect(screen.getByText('Admin')).toBeInTheDocument();
  310. const apiMock = mocks[1];
  311. expect(apiMock).toHaveBeenCalledWith(
  312. `/organizations/org-slug/members/`,
  313. expect.objectContaining({
  314. data: {email: initialEmail, role, teams: [TeamFixture().slug]},
  315. })
  316. );
  317. expect(
  318. await screen.findByText(textWithMarkupMatcher('Sent 1 invite'))
  319. ).toBeInTheDocument();
  320. });
  321. describe('member invite request mode', function () {
  322. it('has adjusted wording', async function () {
  323. setupView({orgAccess: []});
  324. expect(
  325. await screen.findByRole('button', {name: 'Send invite request'})
  326. ).toBeInTheDocument();
  327. });
  328. it('POSTS to the invite-request endpoint', async function () {
  329. const createInviteRequestMock = (client, orgSlug, _) => {
  330. return client.addMockResponse({
  331. url: `/organizations/${orgSlug}/invite-requests/`,
  332. method: 'POST',
  333. });
  334. };
  335. // Use initial data so we don't have to setup as much stuff
  336. const initialEmail = 'test@gmail.com';
  337. const initialData = [{emails: new Set([initialEmail])}];
  338. const {mocks} = setupView({
  339. orgAccess: [],
  340. mockApiResponses: [defaultMockOrganizationRoles, createInviteRequestMock],
  341. modalProps: {
  342. ...defaultMockModalProps,
  343. initialData,
  344. },
  345. });
  346. await waitFor(() => {
  347. expect(screen.getByText(initialEmail)).toBeInTheDocument();
  348. });
  349. await userEvent.click(screen.getByRole('button', {name: 'Send invite request'}));
  350. const apiMock = mocks[1];
  351. expect(apiMock).toHaveBeenCalledTimes(1);
  352. });
  353. });
  354. });