ruleForm.spec.jsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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('Creating a new rule', () => {
  75. let createRule;
  76. beforeEach(() => {
  77. createRule = MockApiClient.addMockResponse({
  78. url: '/projects/org-slug/project-slug/alert-rules/',
  79. method: 'POST',
  80. });
  81. });
  82. /**
  83. * Note this isn't necessarily the desired behavior, as it is just documenting the behavior
  84. */
  85. it('creates a rule', async () => {
  86. const rule = TestStubs.MetricRule();
  87. createWrapper({
  88. rule: {
  89. ...rule,
  90. id: undefined,
  91. eventTypes: ['default'],
  92. },
  93. });
  94. // Clear field
  95. await userEvent.clear(screen.getByPlaceholderText('Enter Alert Name'));
  96. // Enter in name so we can submit
  97. await userEvent.type(
  98. screen.getByPlaceholderText('Enter Alert Name'),
  99. 'Incident Rule'
  100. );
  101. // Set thresholdPeriod
  102. await selectEvent.select(screen.getAllByText('For 1 minute')[0], 'For 10 minutes');
  103. await userEvent.click(screen.getByLabelText('Save Rule'));
  104. expect(createRule).toHaveBeenCalledWith(
  105. expect.anything(),
  106. expect.objectContaining({
  107. data: expect.objectContaining({
  108. name: 'Incident Rule',
  109. projects: ['project-slug'],
  110. eventTypes: ['default'],
  111. thresholdPeriod: 10,
  112. }),
  113. })
  114. );
  115. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  116. });
  117. it('creates a rule with generic_metrics dataset', async () => {
  118. organization.features = [...organization.features, 'mep-rollout-flag'];
  119. const rule = TestStubs.MetricRule();
  120. createWrapper({
  121. rule: {
  122. ...rule,
  123. id: undefined,
  124. aggregate: 'count()',
  125. eventTypes: ['transaction'],
  126. dataset: 'transactions',
  127. },
  128. });
  129. await waitFor(() =>
  130. expect(screen.getByTestId('alert-total-events')).toHaveTextContent(
  131. 'Total Events5'
  132. )
  133. );
  134. await userEvent.click(screen.getByLabelText('Save Rule'));
  135. expect(createRule).toHaveBeenCalledWith(
  136. expect.anything(),
  137. expect.objectContaining({
  138. data: expect.objectContaining({
  139. name: 'My Incident Rule',
  140. projects: ['project-slug'],
  141. aggregate: 'count()',
  142. eventTypes: ['transaction'],
  143. dataset: 'generic_metrics',
  144. thresholdPeriod: 1,
  145. }),
  146. })
  147. );
  148. });
  149. it('switches to custom metric and selects event.type:error', async () => {
  150. organization.features = [...organization.features, 'performance-view'];
  151. const rule = TestStubs.MetricRule();
  152. createWrapper({
  153. rule: {
  154. ...rule,
  155. id: undefined,
  156. eventTypes: ['default'],
  157. },
  158. });
  159. await userEvent.click(screen.getAllByText('Number of Errors').at(1));
  160. await userEvent.click(await screen.findByText('Custom Metric'));
  161. await userEvent.click(screen.getAllByText('event.type:transaction').at(1));
  162. await userEvent.click(await screen.findByText('event.type:error'));
  163. expect(screen.getAllByText('Custom Metric')).toHaveLength(2);
  164. await userEvent.click(screen.getByLabelText('Save Rule'));
  165. expect(createRule).toHaveBeenLastCalledWith(
  166. expect.anything(),
  167. expect.objectContaining({
  168. data: expect.objectContaining({
  169. aggregate: 'count()',
  170. alertType: 'custom',
  171. dataset: 'events',
  172. datasource: 'error',
  173. environment: null,
  174. eventTypes: ['error'],
  175. name: 'My Incident Rule',
  176. projectId: '2',
  177. projects: ['project-slug'],
  178. query: '',
  179. }),
  180. })
  181. );
  182. });
  183. });
  184. describe('Editing a rule', () => {
  185. let editRule;
  186. let editTrigger;
  187. const rule = TestStubs.MetricRule();
  188. beforeEach(() => {
  189. editRule = MockApiClient.addMockResponse({
  190. url: `/projects/org-slug/project-slug/alert-rules/${rule.id}/`,
  191. method: 'PUT',
  192. body: rule,
  193. });
  194. editTrigger = MockApiClient.addMockResponse({
  195. url: `/organizations/org-slug/alert-rules/${rule.id}/triggers/1/`,
  196. method: 'PUT',
  197. body: TestStubs.IncidentTrigger({id: 1}),
  198. });
  199. });
  200. afterEach(() => {
  201. editRule.mockReset();
  202. editTrigger.mockReset();
  203. });
  204. it('edits metric', async () => {
  205. createWrapper({
  206. ruleId: rule.id,
  207. rule,
  208. });
  209. // Clear field
  210. await userEvent.clear(screen.getByPlaceholderText('Enter Alert Name'));
  211. await userEvent.type(screen.getByPlaceholderText('Enter Alert Name'), 'new name');
  212. await userEvent.click(screen.getByLabelText('Save Rule'));
  213. expect(editRule).toHaveBeenLastCalledWith(
  214. expect.anything(),
  215. expect.objectContaining({
  216. data: expect.objectContaining({
  217. name: 'new name',
  218. }),
  219. })
  220. );
  221. });
  222. it('switches from percent change to count', async () => {
  223. createWrapper({
  224. ruleId: rule.id,
  225. rule: {
  226. ...rule,
  227. timeWindow: 60,
  228. comparisonDelta: 100,
  229. eventTypes: ['error'],
  230. resolution: 2,
  231. },
  232. });
  233. expect(screen.getByLabelText('Static: above or below {x}')).not.toBeChecked();
  234. await userEvent.click(screen.getByText('Static: above or below {x}'));
  235. await waitFor(() =>
  236. expect(screen.getByLabelText('Static: above or below {x}')).toBeChecked()
  237. );
  238. await userEvent.click(screen.getByLabelText('Save Rule'));
  239. expect(editRule).toHaveBeenLastCalledWith(
  240. expect.anything(),
  241. expect.objectContaining({
  242. data: expect.objectContaining({
  243. // Comparison delta is reset
  244. comparisonDelta: null,
  245. }),
  246. })
  247. );
  248. });
  249. it('switches event type from error to default', async () => {
  250. createWrapper({
  251. ruleId: rule.id,
  252. rule: {
  253. ...rule,
  254. eventTypes: ['error', 'default'],
  255. },
  256. });
  257. await userEvent.click(screen.getByText('event.type:error OR event.type:default'));
  258. await userEvent.click(await screen.findByText('event.type:default'));
  259. expect(screen.getAllByText('Number of Errors')).toHaveLength(2);
  260. await userEvent.click(screen.getByLabelText('Save Rule'));
  261. expect(editRule).toHaveBeenLastCalledWith(
  262. expect.anything(),
  263. expect.objectContaining({
  264. data: expect.objectContaining({
  265. eventTypes: ['default'],
  266. }),
  267. })
  268. );
  269. });
  270. });
  271. describe('Slack async lookup', () => {
  272. const uuid = 'xxxx-xxxx-xxxx';
  273. beforeEach(() => {
  274. jest.useFakeTimers();
  275. });
  276. afterEach(() => {
  277. jest.runOnlyPendingTimers();
  278. jest.useRealTimers();
  279. });
  280. it('success status updates the rule', async () => {
  281. const alertRule = TestStubs.MetricRule({name: 'Slack Alert Rule'});
  282. MockApiClient.addMockResponse({
  283. url: `/projects/org-slug/project-slug/alert-rules/${alertRule.id}/`,
  284. method: 'PUT',
  285. body: {uuid},
  286. statusCode: 202,
  287. });
  288. MockApiClient.addMockResponse({
  289. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  290. body: {
  291. status: 'success',
  292. alertRule,
  293. },
  294. });
  295. const onSubmitSuccess = jest.fn();
  296. createWrapper({
  297. ruleId: alertRule.id,
  298. rule: alertRule,
  299. onSubmitSuccess,
  300. });
  301. await userEvent.type(
  302. screen.getByPlaceholderText('Enter Alert Name'),
  303. 'Slack Alert Rule',
  304. {delay: null}
  305. );
  306. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  307. expect(screen.getByTestId('loading-indicator')).toBeInTheDocument();
  308. act(jest.runAllTimers);
  309. await waitFor(
  310. () => {
  311. expect(onSubmitSuccess).toHaveBeenCalledWith(
  312. expect.objectContaining({
  313. id: alertRule.id,
  314. name: alertRule.name,
  315. }),
  316. expect.anything()
  317. );
  318. },
  319. {timeout: 2000, interval: 10}
  320. );
  321. });
  322. it('pending status keeps loading true', () => {
  323. const alertRule = TestStubs.MetricRule({name: 'Slack Alert Rule'});
  324. MockApiClient.addMockResponse({
  325. url: `/projects/org-slug/project-slug/alert-rules/${alertRule.id}/`,
  326. method: 'PUT',
  327. body: {uuid},
  328. statusCode: 202,
  329. });
  330. MockApiClient.addMockResponse({
  331. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  332. body: {
  333. status: 'pending',
  334. },
  335. });
  336. const onSubmitSuccess = jest.fn();
  337. createWrapper({
  338. ruleId: alertRule.id,
  339. rule: alertRule,
  340. onSubmitSuccess,
  341. });
  342. expect(screen.getByTestId('loading-indicator')).toBeInTheDocument();
  343. expect(onSubmitSuccess).not.toHaveBeenCalled();
  344. });
  345. it('failed status renders error message', async () => {
  346. const alertRule = TestStubs.MetricRule({name: 'Slack Alert Rule'});
  347. MockApiClient.addMockResponse({
  348. url: `/projects/org-slug/project-slug/alert-rules/${alertRule.id}/`,
  349. method: 'PUT',
  350. body: {uuid},
  351. statusCode: 202,
  352. });
  353. MockApiClient.addMockResponse({
  354. url: `/projects/org-slug/project-slug/alert-rule-task/${uuid}/`,
  355. body: {
  356. status: 'failed',
  357. error: 'An error occurred',
  358. },
  359. });
  360. const onSubmitSuccess = jest.fn();
  361. createWrapper({
  362. ruleId: alertRule.id,
  363. rule: alertRule,
  364. onSubmitSuccess,
  365. });
  366. await userEvent.type(
  367. screen.getByPlaceholderText('Enter Alert Name'),
  368. 'Slack Alert Rule',
  369. {delay: null}
  370. );
  371. await userEvent.click(screen.getByLabelText('Save Rule'), {delay: null});
  372. act(jest.runAllTimers);
  373. await waitFor(
  374. () => {
  375. expect(addErrorMessage).toHaveBeenCalledWith('An error occurred');
  376. },
  377. {timeout: 2000, interval: 10}
  378. );
  379. expect(onSubmitSuccess).not.toHaveBeenCalled();
  380. });
  381. });
  382. });