ruleForm.spec.jsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. import selectEvent from 'react-select-event';
  2. import {initializeOrg} from 'sentry-test/initializeOrg';
  3. import {act, render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
  4. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  5. import {metric} from 'sentry/utils/analytics';
  6. import RuleFormContainer from 'sentry/views/alerts/rules/metric/ruleForm';
  7. jest.mock('sentry/actionCreators/indicator');
  8. jest.mock('sentry/utils/analytics', () => ({
  9. metric: {
  10. startTransaction: jest.fn(() => ({
  11. setTag: jest.fn(),
  12. setData: jest.fn(),
  13. })),
  14. endTransaction: jest.fn(),
  15. },
  16. }));
  17. describe('Incident Rules Form', () => {
  18. let organization, project, routerContext;
  19. const createWrapper = props =>
  20. render(
  21. <RuleFormContainer
  22. params={{orgId: organization.slug, projectId: project.slug}}
  23. organization={organization}
  24. project={project}
  25. {...props}
  26. />,
  27. {context: routerContext}
  28. );
  29. beforeEach(() => {
  30. const initialData = initializeOrg({
  31. organization: {features: ['metric-alert-threshold-period', 'change-alerts']},
  32. });
  33. organization = initialData.organization;
  34. project = initialData.project;
  35. routerContext = initialData.routerContext;
  36. MockApiClient.addMockResponse({
  37. url: '/organizations/org-slug/tags/',
  38. body: [],
  39. });
  40. MockApiClient.addMockResponse({
  41. url: '/organizations/org-slug/users/',
  42. body: [],
  43. });
  44. MockApiClient.addMockResponse({
  45. url: '/projects/org-slug/project-slug/environments/',
  46. body: [],
  47. });
  48. MockApiClient.addMockResponse({
  49. url: '/organizations/org-slug/events-stats/',
  50. body: TestStubs.EventsStats({
  51. isMetricsData: true,
  52. }),
  53. });
  54. MockApiClient.addMockResponse({
  55. url: '/organizations/org-slug/events-meta/',
  56. body: {count: 5},
  57. });
  58. MockApiClient.addMockResponse({
  59. url: '/organizations/org-slug/alert-rules/available-actions/',
  60. body: [
  61. {
  62. allowedTargetTypes: ['user', 'team'],
  63. integrationName: null,
  64. type: 'email',
  65. integrationId: null,
  66. },
  67. ],
  68. });
  69. });
  70. afterEach(() => {
  71. MockApiClient.clearMockResponses();
  72. jest.clearAllMocks();
  73. });
  74. describe('Viewing the rule', () => {
  75. const rule = TestStubs.MetricRule();
  76. const permissionAlertText =
  77. 'These settings can only be edited by users with the organization-level owner, manager, or team-level admin roles.';
  78. it('is enabled without org-level alerts:write', () => {
  79. organization.access = [];
  80. project.access = [];
  81. createWrapper({rule});
  82. expect(screen.queryByText(permissionAlertText)).toBeInTheDocument();
  83. expect(screen.queryByLabelText('Save Rule')).toBeDisabled();
  84. });
  85. it('is enabled with org-level alerts:write', () => {
  86. organization.access = ['alerts:write'];
  87. project.access = [];
  88. createWrapper({rule});
  89. expect(screen.queryByText(permissionAlertText)).not.toBeInTheDocument();
  90. expect(screen.queryByLabelText('Save Rule')).toBeEnabled();
  91. });
  92. it('is enabled with project-level alerts:write', () => {
  93. organization.access = [];
  94. project.access = ['alerts:write'];
  95. createWrapper({rule});
  96. expect(screen.queryByText(permissionAlertText)).not.toBeInTheDocument();
  97. expect(screen.queryByLabelText('Save Rule')).toBeEnabled();
  98. });
  99. });
  100. describe('Creating a new rule', () => {
  101. let createRule;
  102. beforeEach(() => {
  103. createRule = MockApiClient.addMockResponse({
  104. url: '/projects/org-slug/project-slug/alert-rules/',
  105. method: 'POST',
  106. });
  107. });
  108. /**
  109. * Note this isn't necessarily the desired behavior, as it is just documenting the behavior
  110. */
  111. it('creates a rule', async () => {
  112. const rule = TestStubs.MetricRule();
  113. createWrapper({
  114. rule: {
  115. ...rule,
  116. id: undefined,
  117. eventTypes: ['default'],
  118. },
  119. });
  120. // Clear field
  121. await userEvent.clear(screen.getByPlaceholderText('Enter Alert Name'));
  122. // Enter in name so we can submit
  123. await userEvent.type(
  124. screen.getByPlaceholderText('Enter Alert Name'),
  125. 'Incident Rule'
  126. );
  127. // Set thresholdPeriod
  128. await selectEvent.select(screen.getAllByText('For 1 minute')[0], 'For 10 minutes');
  129. await userEvent.click(screen.getByLabelText('Save Rule'));
  130. expect(createRule).toHaveBeenCalledWith(
  131. expect.anything(),
  132. expect.objectContaining({
  133. data: expect.objectContaining({
  134. name: 'Incident Rule',
  135. projects: ['project-slug'],
  136. eventTypes: ['default'],
  137. thresholdPeriod: 10,
  138. }),
  139. })
  140. );
  141. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  142. });
  143. it('creates a rule with generic_metrics dataset', async () => {
  144. organization.features = [...organization.features, 'mep-rollout-flag'];
  145. const rule = TestStubs.MetricRule();
  146. createWrapper({
  147. rule: {
  148. ...rule,
  149. id: undefined,
  150. aggregate: 'count()',
  151. eventTypes: ['transaction'],
  152. dataset: 'transactions',
  153. },
  154. });
  155. await waitFor(() =>
  156. expect(screen.getByTestId('alert-total-events')).toHaveTextContent(
  157. 'Total Events5'
  158. )
  159. );
  160. await userEvent.click(screen.getByLabelText('Save Rule'));
  161. expect(createRule).toHaveBeenCalledWith(
  162. expect.anything(),
  163. expect.objectContaining({
  164. data: expect.objectContaining({
  165. name: 'My Incident Rule',
  166. projects: ['project-slug'],
  167. aggregate: 'count()',
  168. eventTypes: ['transaction'],
  169. dataset: 'generic_metrics',
  170. thresholdPeriod: 1,
  171. }),
  172. })
  173. );
  174. });
  175. it('switches to custom metric and selects event.type:error', async () => {
  176. organization.features = [...organization.features, 'performance-view'];
  177. const rule = TestStubs.MetricRule();
  178. createWrapper({
  179. rule: {
  180. ...rule,
  181. id: undefined,
  182. eventTypes: ['default'],
  183. },
  184. });
  185. await userEvent.click(screen.getAllByText('Number of Errors').at(1));
  186. await userEvent.click(await screen.findByText('Custom Metric'));
  187. await userEvent.click(screen.getAllByText('event.type:transaction').at(1));
  188. await userEvent.click(await screen.findByText('event.type:error'));
  189. expect(screen.getAllByText('Custom Metric')).toHaveLength(2);
  190. await userEvent.click(screen.getByLabelText('Save Rule'));
  191. expect(createRule).toHaveBeenLastCalledWith(
  192. expect.anything(),
  193. expect.objectContaining({
  194. data: expect.objectContaining({
  195. aggregate: 'count()',
  196. alertType: 'custom',
  197. dataset: 'events',
  198. datasource: 'error',
  199. environment: null,
  200. eventTypes: ['error'],
  201. name: 'My Incident Rule',
  202. projectId: '2',
  203. projects: ['project-slug'],
  204. query: '',
  205. }),
  206. })
  207. );
  208. });
  209. });
  210. describe('Editing a rule', () => {
  211. let editRule;
  212. let editTrigger;
  213. const rule = TestStubs.MetricRule();
  214. beforeEach(() => {
  215. editRule = MockApiClient.addMockResponse({
  216. url: `/projects/org-slug/project-slug/alert-rules/${rule.id}/`,
  217. method: 'PUT',
  218. body: rule,
  219. });
  220. editTrigger = MockApiClient.addMockResponse({
  221. url: `/organizations/org-slug/alert-rules/${rule.id}/triggers/1/`,
  222. method: 'PUT',
  223. body: TestStubs.IncidentTrigger({id: 1}),
  224. });
  225. });
  226. afterEach(() => {
  227. editRule.mockReset();
  228. editTrigger.mockReset();
  229. });
  230. it('edits metric', async () => {
  231. createWrapper({
  232. ruleId: rule.id,
  233. rule,
  234. });
  235. // Clear field
  236. await userEvent.clear(screen.getByPlaceholderText('Enter Alert Name'));
  237. await userEvent.type(screen.getByPlaceholderText('Enter Alert Name'), 'new name');
  238. await userEvent.click(screen.getByLabelText('Save Rule'));
  239. expect(editRule).toHaveBeenLastCalledWith(
  240. expect.anything(),
  241. expect.objectContaining({
  242. data: expect.objectContaining({
  243. name: 'new name',
  244. }),
  245. })
  246. );
  247. });
  248. it('switches from percent change to count', async () => {
  249. createWrapper({
  250. ruleId: rule.id,
  251. rule: {
  252. ...rule,
  253. timeWindow: 60,
  254. comparisonDelta: 100,
  255. eventTypes: ['error'],
  256. resolution: 2,
  257. },
  258. });
  259. expect(screen.getByLabelText('Static: above or below {x}')).not.toBeChecked();
  260. await userEvent.click(screen.getByText('Static: above or below {x}'));
  261. await waitFor(() =>
  262. expect(screen.getByLabelText('Static: above or below {x}')).toBeChecked()
  263. );
  264. await userEvent.click(screen.getByLabelText('Save Rule'));
  265. expect(editRule).toHaveBeenLastCalledWith(
  266. expect.anything(),
  267. expect.objectContaining({
  268. data: expect.objectContaining({
  269. // Comparison delta is reset
  270. comparisonDelta: null,
  271. }),
  272. })
  273. );
  274. });
  275. it('switches event type from error to default', async () => {
  276. createWrapper({
  277. ruleId: rule.id,
  278. rule: {
  279. ...rule,
  280. eventTypes: ['error', 'default'],
  281. },
  282. });
  283. await userEvent.click(screen.getByText('event.type:error OR event.type:default'));
  284. await userEvent.click(await screen.findByText('event.type:default'));
  285. expect(screen.getAllByText('Number of Errors')).toHaveLength(2);
  286. await userEvent.click(screen.getByLabelText('Save Rule'));
  287. expect(editRule).toHaveBeenLastCalledWith(
  288. expect.anything(),
  289. expect.objectContaining({
  290. data: expect.objectContaining({
  291. eventTypes: ['default'],
  292. }),
  293. })
  294. );
  295. });
  296. });
  297. describe('Slack async lookup', () => {
  298. const uuid = 'xxxx-xxxx-xxxx';
  299. beforeEach(() => {
  300. jest.useFakeTimers();
  301. });
  302. afterEach(() => {
  303. jest.runOnlyPendingTimers();
  304. jest.useRealTimers();
  305. });
  306. it('success status updates the rule', async () => {
  307. const alertRule = TestStubs.MetricRule({name: 'Slack Alert Rule'});
  308. MockApiClient.addMockResponse({
  309. url: `/projects/org-slug/project-slug/alert-rules/${alertRule.id}/`,
  310. method: 'PUT',
  311. body: {uuid},
  312. statusCode: 202,
  313. });
  314. MockApiClient.addMockResponse({
  315. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  316. body: {
  317. status: 'success',
  318. alertRule,
  319. },
  320. });
  321. const onSubmitSuccess = jest.fn();
  322. createWrapper({
  323. ruleId: alertRule.id,
  324. rule: alertRule,
  325. onSubmitSuccess,
  326. });
  327. await userEvent.type(
  328. screen.getByPlaceholderText('Enter Alert Name'),
  329. 'Slack Alert Rule',
  330. {delay: null}
  331. );
  332. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  333. expect(screen.getByTestId('loading-indicator')).toBeInTheDocument();
  334. act(jest.runAllTimers);
  335. await waitFor(
  336. () => {
  337. expect(onSubmitSuccess).toHaveBeenCalledWith(
  338. expect.objectContaining({
  339. id: alertRule.id,
  340. name: alertRule.name,
  341. }),
  342. expect.anything()
  343. );
  344. },
  345. {timeout: 2000, interval: 10}
  346. );
  347. });
  348. it('pending status keeps loading true', () => {
  349. const alertRule = TestStubs.MetricRule({name: 'Slack Alert Rule'});
  350. MockApiClient.addMockResponse({
  351. url: `/projects/org-slug/project-slug/alert-rules/${alertRule.id}/`,
  352. method: 'PUT',
  353. body: {uuid},
  354. statusCode: 202,
  355. });
  356. MockApiClient.addMockResponse({
  357. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  358. body: {
  359. status: 'pending',
  360. },
  361. });
  362. const onSubmitSuccess = jest.fn();
  363. createWrapper({
  364. ruleId: alertRule.id,
  365. rule: alertRule,
  366. onSubmitSuccess,
  367. });
  368. expect(screen.getByTestId('loading-indicator')).toBeInTheDocument();
  369. expect(onSubmitSuccess).not.toHaveBeenCalled();
  370. });
  371. it('failed status renders error message', async () => {
  372. const alertRule = TestStubs.MetricRule({name: 'Slack Alert Rule'});
  373. MockApiClient.addMockResponse({
  374. url: `/projects/org-slug/project-slug/alert-rules/${alertRule.id}/`,
  375. method: 'PUT',
  376. body: {uuid},
  377. statusCode: 202,
  378. });
  379. MockApiClient.addMockResponse({
  380. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  381. body: {
  382. status: 'failed',
  383. error: 'An error occurred',
  384. },
  385. });
  386. const onSubmitSuccess = jest.fn();
  387. createWrapper({
  388. ruleId: alertRule.id,
  389. rule: alertRule,
  390. onSubmitSuccess,
  391. });
  392. await userEvent.type(
  393. screen.getByPlaceholderText('Enter Alert Name'),
  394. 'Slack Alert Rule',
  395. {delay: null}
  396. );
  397. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  398. act(jest.runAllTimers);
  399. await waitFor(
  400. () => {
  401. expect(addErrorMessage).toHaveBeenCalledWith('An error occurred');
  402. },
  403. {timeout: 2000, interval: 10}
  404. );
  405. expect(onSubmitSuccess).not.toHaveBeenCalled();
  406. });
  407. });
  408. });