index.spec.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. import type {PlainRoute} from 'react-router';
  2. import {browserHistory} from 'react-router';
  3. import selectEvent from 'react-select-event';
  4. import moment from 'moment';
  5. import {EnvironmentsFixture} from 'sentry-fixture/environments';
  6. import {ProjectFixture} from 'sentry-fixture/project';
  7. import {ProjectAlertRuleFixture} from 'sentry-fixture/projectAlertRule';
  8. import {ProjectAlertRuleConfigurationFixture} from 'sentry-fixture/projectAlertRuleConfiguration';
  9. import {RouteComponentPropsFixture} from 'sentry-fixture/routeComponentPropsFixture';
  10. import {initializeOrg} from 'sentry-test/initializeOrg';
  11. import {
  12. render,
  13. renderGlobalModal,
  14. screen,
  15. userEvent,
  16. waitFor,
  17. within,
  18. } from 'sentry-test/reactTestingLibrary';
  19. import {
  20. addErrorMessage,
  21. addLoadingMessage,
  22. addSuccessMessage,
  23. } from 'sentry/actionCreators/indicator';
  24. import {updateOnboardingTask} from 'sentry/actionCreators/onboardingTasks';
  25. import ProjectsStore from 'sentry/stores/projectsStore';
  26. import {metric} from 'sentry/utils/analytics';
  27. import IssueRuleEditor from 'sentry/views/alerts/rules/issue';
  28. import {permissionAlertText} from 'sentry/views/settings/project/permissionAlert';
  29. import ProjectAlerts from 'sentry/views/settings/projectAlerts';
  30. jest.unmock('sentry/utils/recreateRoute');
  31. jest.mock('sentry/actionCreators/onboardingTasks');
  32. jest.mock('sentry/actionCreators/indicator', () => ({
  33. addSuccessMessage: jest.fn(),
  34. addErrorMessage: jest.fn(),
  35. addLoadingMessage: jest.fn(),
  36. }));
  37. jest.mock('sentry/utils/analytics', () => ({
  38. metric: {
  39. startTransaction: jest.fn(() => ({
  40. setTag: jest.fn(),
  41. setData: jest.fn(),
  42. })),
  43. endTransaction: jest.fn(),
  44. mark: jest.fn(),
  45. measure: jest.fn(),
  46. },
  47. trackAnalytics: jest.fn(),
  48. }));
  49. const projectAlertRuleDetailsRoutes: PlainRoute<any>[] = [
  50. {
  51. path: '/',
  52. },
  53. {
  54. path: '/settings/',
  55. indexRoute: {},
  56. },
  57. {
  58. path: ':orgId/',
  59. },
  60. {
  61. path: 'projects/:projectId/',
  62. },
  63. {},
  64. {
  65. indexRoute: {},
  66. },
  67. {
  68. path: 'alerts/',
  69. indexRoute: {},
  70. },
  71. {
  72. path: 'rules/',
  73. indexRoute: {},
  74. childRoutes: [{path: 'new/'}, {path: ':ruleId/'}],
  75. },
  76. {path: ':ruleId/'},
  77. ];
  78. const createWrapper = (props = {}) => {
  79. const {organization, project, routerContext, router} = initializeOrg(props);
  80. const params = {
  81. projectId: project.slug,
  82. organizationId: organization.slug,
  83. ruleId: router.location.query.createFromDuplicate ? undefined : '1',
  84. };
  85. const onChangeTitleMock = jest.fn();
  86. const wrapper = render(
  87. <ProjectAlerts
  88. {...RouteComponentPropsFixture()}
  89. organization={organization}
  90. project={project}
  91. params={params}
  92. >
  93. <IssueRuleEditor
  94. route={RouteComponentPropsFixture().route}
  95. routeParams={RouteComponentPropsFixture().routeParams}
  96. params={params}
  97. location={router.location}
  98. routes={projectAlertRuleDetailsRoutes}
  99. router={router}
  100. members={[]}
  101. onChangeTitle={onChangeTitleMock}
  102. project={project}
  103. userTeamIds={[]}
  104. />
  105. </ProjectAlerts>,
  106. {context: routerContext, organization}
  107. );
  108. return {
  109. wrapper,
  110. organization,
  111. project,
  112. onChangeTitleMock,
  113. router,
  114. };
  115. };
  116. describe('IssueRuleEditor', function () {
  117. beforeEach(function () {
  118. MockApiClient.clearMockResponses();
  119. browserHistory.replace = jest.fn();
  120. MockApiClient.addMockResponse({
  121. url: '/projects/org-slug/project-slug/rules/configuration/',
  122. body: ProjectAlertRuleConfigurationFixture(),
  123. });
  124. MockApiClient.addMockResponse({
  125. url: '/projects/org-slug/project-slug/rules/1/',
  126. body: ProjectAlertRuleFixture(),
  127. });
  128. MockApiClient.addMockResponse({
  129. url: '/projects/org-slug/project-slug/environments/',
  130. body: EnvironmentsFixture(),
  131. });
  132. MockApiClient.addMockResponse({
  133. url: `/projects/org-slug/project-slug/?expand=hasAlertIntegration`,
  134. body: {},
  135. });
  136. MockApiClient.addMockResponse({
  137. url: `/projects/org-slug/project-slug/ownership/`,
  138. method: 'GET',
  139. body: {
  140. fallthrough: false,
  141. autoAssignment: false,
  142. },
  143. });
  144. MockApiClient.addMockResponse({
  145. url: '/projects/org-slug/project-slug/rules/preview/',
  146. method: 'POST',
  147. body: [],
  148. });
  149. ProjectsStore.loadInitialData([ProjectFixture()]);
  150. });
  151. afterEach(function () {
  152. jest.clearAllMocks();
  153. ProjectsStore.reset();
  154. });
  155. describe('Viewing the rule', () => {
  156. it('is visible without org-level alerts:write', async () => {
  157. createWrapper({
  158. organization: {access: []},
  159. project: {access: []},
  160. });
  161. expect(await screen.findByText(permissionAlertText)).toBeInTheDocument();
  162. expect(screen.queryByLabelText('Save Rule')).toBeDisabled();
  163. });
  164. it('is enabled with org-level alerts:write', async () => {
  165. createWrapper({
  166. organization: {access: ['alerts:write']},
  167. project: {access: []},
  168. });
  169. expect(await screen.findByLabelText('Save Rule')).toBeEnabled();
  170. expect(screen.queryByText(permissionAlertText)).not.toBeInTheDocument();
  171. });
  172. it('is enabled with project-level alerts:write', async () => {
  173. createWrapper({
  174. organization: {access: []},
  175. project: {access: ['alerts:write']},
  176. });
  177. expect(await screen.findByLabelText('Save Rule')).toBeEnabled();
  178. expect(screen.queryByText(permissionAlertText)).not.toBeInTheDocument();
  179. });
  180. });
  181. describe('Edit Rule', function () {
  182. let mock;
  183. const endpoint = '/projects/org-slug/project-slug/rules/1/';
  184. beforeEach(function () {
  185. mock = MockApiClient.addMockResponse({
  186. url: endpoint,
  187. method: 'PUT',
  188. body: ProjectAlertRuleFixture(),
  189. });
  190. });
  191. it('gets correct rule name', async function () {
  192. const rule = ProjectAlertRuleFixture();
  193. mock = MockApiClient.addMockResponse({
  194. url: endpoint,
  195. method: 'GET',
  196. body: rule,
  197. });
  198. const {onChangeTitleMock} = createWrapper();
  199. await waitFor(() => expect(mock).toHaveBeenCalled());
  200. expect(onChangeTitleMock).toHaveBeenCalledWith(rule.name);
  201. });
  202. it('deletes rule', async function () {
  203. const deleteMock = MockApiClient.addMockResponse({
  204. url: endpoint,
  205. method: 'DELETE',
  206. body: {},
  207. });
  208. createWrapper();
  209. renderGlobalModal();
  210. await userEvent.click(screen.getByLabelText('Delete Rule'));
  211. expect(
  212. await screen.findByText(/Are you sure you want to delete "My alert rule"\?/)
  213. ).toBeInTheDocument();
  214. await userEvent.click(screen.getByTestId('confirm-button'));
  215. await waitFor(() => expect(deleteMock).toHaveBeenCalled());
  216. expect(browserHistory.replace).toHaveBeenCalledWith(
  217. '/settings/org-slug/projects/project-slug/alerts/'
  218. );
  219. });
  220. it('sends correct environment value', async function () {
  221. createWrapper();
  222. await selectEvent.select(screen.getByText('staging'), 'production');
  223. await userEvent.click(screen.getByText('Save Rule'));
  224. await waitFor(() =>
  225. expect(mock).toHaveBeenCalledWith(
  226. endpoint,
  227. expect.objectContaining({
  228. data: expect.objectContaining({environment: 'production'}),
  229. })
  230. )
  231. );
  232. expect(metric.startTransaction).toHaveBeenCalledTimes(1);
  233. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  234. });
  235. it('strips environment value if "All environments" is selected', async function () {
  236. createWrapper();
  237. await selectEvent.select(screen.getByText('staging'), 'All Environments');
  238. await userEvent.click(screen.getByText('Save Rule'));
  239. await waitFor(() => expect(mock).toHaveBeenCalledTimes(1));
  240. expect(mock).not.toHaveBeenCalledWith(
  241. endpoint,
  242. expect.objectContaining({
  243. data: expect.objectContaining({environment: '__all_environments__'}),
  244. })
  245. );
  246. expect(metric.startTransaction).toHaveBeenCalledTimes(1);
  247. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  248. });
  249. it('updates the alert onboarding task', async function () {
  250. createWrapper();
  251. await userEvent.click(screen.getByText('Save Rule'));
  252. await waitFor(() => expect(updateOnboardingTask).toHaveBeenCalledTimes(1));
  253. expect(metric.startTransaction).toHaveBeenCalledTimes(1);
  254. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  255. });
  256. it('renders multiple sentry apps at the same time', async () => {
  257. const linearApp = {
  258. id: 'sentry.rules.actions.notify_event_sentry_app.NotifyEventSentryAppAction',
  259. enabled: true,
  260. actionType: 'sentryapp',
  261. service: 'linear',
  262. sentryAppInstallationUuid: 'linear-d864bc2a8755',
  263. prompt: 'Linear',
  264. label: 'Create a Linear issue with these ',
  265. formFields: {
  266. type: 'alert-rule-settings',
  267. uri: '/hooks/sentry/alert-rule-action',
  268. description:
  269. 'When the alert fires automatically create a Linear issue with the following properties.',
  270. required_fields: [
  271. {
  272. name: 'teamId',
  273. label: 'Team',
  274. type: 'select',
  275. uri: '/hooks/sentry/issues/teams',
  276. choices: [['test-6f0b2b4d402b', 'Sentry']],
  277. },
  278. ],
  279. optional_fields: [
  280. // Optional fields removed
  281. ],
  282. },
  283. };
  284. const threadsApp = {
  285. id: 'sentry.rules.actions.notify_event_sentry_app.NotifyEventSentryAppAction',
  286. enabled: true,
  287. actionType: 'sentryapp',
  288. service: 'threads',
  289. sentryAppInstallationUuid: 'threads-987c470e50cc',
  290. prompt: 'Threads',
  291. label: 'Post to a Threads channel with these ',
  292. formFields: {
  293. type: 'alert-rule-settings',
  294. uri: '/sentry/saveAlert',
  295. required_fields: [
  296. {
  297. type: 'select',
  298. label: 'Channel',
  299. name: 'channel',
  300. async: true,
  301. uri: '/sentry/channels',
  302. choices: [],
  303. },
  304. ],
  305. },
  306. };
  307. MockApiClient.addMockResponse({
  308. url: '/projects/org-slug/project-slug/rules/configuration/',
  309. body: {actions: [linearApp, threadsApp], conditions: [], filters: []},
  310. });
  311. createWrapper();
  312. await selectEvent.select(screen.getByText('Add action...'), 'Threads');
  313. await selectEvent.select(screen.getByText('Add action...'), 'Linear');
  314. expect(screen.getByText('Create a Linear issue with these')).toBeInTheDocument();
  315. expect(
  316. screen.getByText('Post to a Threads channel with these')
  317. ).toBeInTheDocument();
  318. });
  319. it('opts out of the alert being disabled', async function () {
  320. MockApiClient.addMockResponse({
  321. url: '/projects/org-slug/project-slug/rules/1/',
  322. body: ProjectAlertRuleFixture({
  323. status: 'disabled',
  324. disableDate: moment().add(1, 'day').toISOString(),
  325. }),
  326. });
  327. createWrapper();
  328. await userEvent.click(screen.getByText('Save Rule'));
  329. await waitFor(() =>
  330. expect(mock).toHaveBeenCalledWith(
  331. endpoint,
  332. expect.objectContaining({
  333. data: expect.objectContaining({optOutEdit: true}),
  334. })
  335. )
  336. );
  337. });
  338. it('renders environment selector in adopted release filter', async function () {
  339. createWrapper({project: ProjectFixture({environments: ['production', 'staging']})});
  340. // Add the adopted release filter
  341. await selectEvent.select(
  342. screen.getByText('Add optional filter...'),
  343. /The {oldest_or_newest} release associated/
  344. );
  345. const filtersContainer = screen.getByTestId('rule-filters');
  346. // Production environment is preselected because it's the first option.
  347. // staging should also be selectable.
  348. selectEvent.select(
  349. within(filtersContainer).getAllByText('production')[0],
  350. 'staging'
  351. );
  352. });
  353. });
  354. describe('Edit Rule: Slack Channel Look Up', function () {
  355. const uuid = 'xxxx-xxxx-xxxx';
  356. beforeEach(function () {
  357. jest.useFakeTimers();
  358. });
  359. afterEach(function () {
  360. jest.clearAllTimers();
  361. });
  362. it('success status updates the rule', async function () {
  363. const mockSuccess = MockApiClient.addMockResponse({
  364. url: `/projects/org-slug/project-slug/rule-task/${uuid}/`,
  365. body: {status: 'success', rule: ProjectAlertRuleFixture({name: 'Slack Rule'})},
  366. });
  367. MockApiClient.addMockResponse({
  368. url: '/projects/org-slug/project-slug/rules/1/',
  369. method: 'PUT',
  370. statusCode: 202,
  371. body: {uuid},
  372. });
  373. const {router} = createWrapper();
  374. await userEvent.click(screen.getByText('Save Rule'), {delay: null});
  375. await waitFor(() => expect(addLoadingMessage).toHaveBeenCalledTimes(2));
  376. jest.advanceTimersByTime(1000);
  377. await waitFor(() => expect(mockSuccess).toHaveBeenCalledTimes(1));
  378. jest.advanceTimersByTime(1000);
  379. await waitFor(() => expect(addSuccessMessage).toHaveBeenCalledTimes(1));
  380. expect(router.push).toHaveBeenCalledWith({
  381. pathname: '/organizations/org-slug/alerts/rules/project-slug/1/details/',
  382. });
  383. });
  384. it('pending status keeps loading true', async function () {
  385. const pollingMock = MockApiClient.addMockResponse({
  386. url: `/projects/org-slug/project-slug/rule-task/${uuid}/`,
  387. body: {status: 'pending'},
  388. });
  389. MockApiClient.addMockResponse({
  390. url: '/projects/org-slug/project-slug/rules/1/',
  391. method: 'PUT',
  392. statusCode: 202,
  393. body: {uuid},
  394. });
  395. createWrapper();
  396. await userEvent.click(screen.getByText('Save Rule'), {delay: null});
  397. await waitFor(() => expect(addLoadingMessage).toHaveBeenCalledTimes(2));
  398. jest.advanceTimersByTime(1000);
  399. await waitFor(() => expect(pollingMock).toHaveBeenCalledTimes(1));
  400. expect(screen.getByTestId('loading-mask')).toBeInTheDocument();
  401. });
  402. it('failed status renders error message', async function () {
  403. const mockFailed = MockApiClient.addMockResponse({
  404. url: `/projects/org-slug/project-slug/rule-task/${uuid}/`,
  405. body: {status: 'failed'},
  406. });
  407. MockApiClient.addMockResponse({
  408. url: '/projects/org-slug/project-slug/rules/1/',
  409. method: 'PUT',
  410. statusCode: 202,
  411. body: {uuid},
  412. });
  413. createWrapper();
  414. await userEvent.click(screen.getByText('Save Rule'), {delay: null});
  415. await waitFor(() => expect(addLoadingMessage).toHaveBeenCalledTimes(2));
  416. jest.advanceTimersByTime(1000);
  417. await waitFor(() => expect(mockFailed).toHaveBeenCalledTimes(1));
  418. expect(screen.getByText('An error occurred')).toBeInTheDocument();
  419. expect(addErrorMessage).toHaveBeenCalledTimes(1);
  420. });
  421. });
  422. describe('Duplicate Rule', function () {
  423. let mock;
  424. const rule = ProjectAlertRuleFixture();
  425. const endpoint = `/projects/org-slug/project-slug/rules/${rule.id}/`;
  426. beforeEach(function () {
  427. mock = MockApiClient.addMockResponse({
  428. url: endpoint,
  429. method: 'GET',
  430. body: rule,
  431. });
  432. });
  433. it('gets correct rule to duplicate and renders fields correctly', async function () {
  434. createWrapper({
  435. organization: {
  436. access: ['alerts:write'],
  437. },
  438. router: {
  439. location: {
  440. query: {
  441. createFromDuplicate: 'true',
  442. duplicateRuleId: `${rule.id}`,
  443. },
  444. },
  445. },
  446. });
  447. expect(await screen.findByTestId('alert-name')).toHaveValue(`${rule.name} copy`);
  448. expect(screen.queryByText('A new issue is created')).toBeInTheDocument();
  449. expect(mock).toHaveBeenCalled();
  450. });
  451. it('does not add FirstSeenEventCondition to a duplicate rule', async function () {
  452. MockApiClient.addMockResponse({
  453. url: endpoint,
  454. method: 'GET',
  455. body: {...rule, conditions: []},
  456. });
  457. createWrapper({
  458. organization: {
  459. access: ['alerts:write'],
  460. },
  461. router: {
  462. location: {
  463. query: {
  464. createFromDuplicate: 'true',
  465. duplicateRuleId: `${rule.id}`,
  466. },
  467. },
  468. },
  469. });
  470. expect(await screen.findByTestId('alert-name')).toHaveValue(`${rule.name} copy`);
  471. expect(screen.queryByText('A new issue is created')).not.toBeInTheDocument();
  472. });
  473. });
  474. });