ruleForm.spec.jsx 11 KB

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