create.spec.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. import selectEvent from 'react-select-event';
  2. import {initializeOrg} from 'sentry-test/initializeOrg';
  3. import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
  4. import ProjectsStore from 'sentry/stores/projectsStore';
  5. import TeamStore from 'sentry/stores/teamStore';
  6. import {metric, trackAnalytics} from 'sentry/utils/analytics';
  7. import AlertsContainer from 'sentry/views/alerts';
  8. import AlertBuilderProjectProvider from 'sentry/views/alerts/builder/projectProvider';
  9. import ProjectAlertsCreate from 'sentry/views/alerts/create';
  10. jest.unmock('sentry/utils/recreateRoute');
  11. // updateOnboardingTask triggers an out of band state update
  12. jest.mock('sentry/actionCreators/onboardingTasks');
  13. jest.mock('sentry/actionCreators/members', () => ({
  14. fetchOrgMembers: jest.fn(() => Promise.resolve([])),
  15. indexMembersByProject: jest.fn(() => {
  16. return {};
  17. }),
  18. }));
  19. jest.mock('react-router');
  20. jest.mock('sentry/utils/analytics', () => ({
  21. metric: {
  22. startTransaction: jest.fn(() => ({
  23. setTag: jest.fn(),
  24. setData: jest.fn(),
  25. })),
  26. endTransaction: jest.fn(),
  27. mark: jest.fn(),
  28. measure: jest.fn(),
  29. },
  30. trackAnalytics: jest.fn(),
  31. }));
  32. describe('ProjectAlertsCreate', function () {
  33. beforeEach(function () {
  34. TeamStore.init();
  35. TeamStore.loadInitialData([], false, null);
  36. MockApiClient.addMockResponse({
  37. url: '/projects/org-slug/project-slug/rules/configuration/',
  38. body: TestStubs.ProjectAlertRuleConfiguration(),
  39. });
  40. MockApiClient.addMockResponse({
  41. url: '/projects/org-slug/project-slug/rules/1/',
  42. body: TestStubs.ProjectAlertRule(),
  43. });
  44. MockApiClient.addMockResponse({
  45. url: '/projects/org-slug/project-slug/environments/',
  46. body: TestStubs.Environments(),
  47. });
  48. MockApiClient.addMockResponse({
  49. url: `/projects/org-slug/project-slug/?expand=hasAlertIntegration`,
  50. body: {},
  51. });
  52. MockApiClient.addMockResponse({
  53. url: `/projects/org-slug/project-slug/ownership/`,
  54. method: 'GET',
  55. body: {
  56. fallthrough: false,
  57. autoAssignment: false,
  58. },
  59. });
  60. MockApiClient.addMockResponse({
  61. url: '/projects/org-slug/project-slug/rules/preview/',
  62. method: 'POST',
  63. body: [],
  64. });
  65. });
  66. afterEach(function () {
  67. MockApiClient.clearMockResponses();
  68. jest.clearAllMocks();
  69. });
  70. const createWrapper = (props = {}, location = {}) => {
  71. const {organization, project, router, routerContext} = initializeOrg(props);
  72. ProjectsStore.loadInitialData([project]);
  73. const params = {orgId: organization.slug, projectId: project.slug};
  74. const wrapper = render(
  75. <AlertsContainer>
  76. <AlertBuilderProjectProvider
  77. {...TestStubs.routeComponentProps()}
  78. params={params}
  79. organization={organization}
  80. hasMetricAlerts={false}
  81. >
  82. <ProjectAlertsCreate
  83. {...TestStubs.routeComponentProps()}
  84. hasMetricAlerts={false}
  85. members={[]}
  86. params={params}
  87. organization={organization}
  88. project={project}
  89. location={TestStubs.location({
  90. pathname: `/organizations/org-slug/alerts/rules/${project.slug}/new/`,
  91. query: {createFromWizard: 'true'},
  92. ...location,
  93. })}
  94. router={router}
  95. />
  96. </AlertBuilderProjectProvider>
  97. </AlertsContainer>,
  98. {organization, context: routerContext}
  99. );
  100. return {
  101. wrapper,
  102. organization,
  103. project,
  104. router,
  105. };
  106. };
  107. it('adds default parameters if wizard was skipped', async function () {
  108. const location = {query: {}};
  109. const wrapper = createWrapper(undefined, location);
  110. await waitFor(() => {
  111. expect(wrapper.router.replace).toHaveBeenCalledWith(
  112. expect.objectContaining({
  113. pathname: '/organizations/org-slug/alerts/new/metric',
  114. query: {
  115. aggregate: 'count()',
  116. dataset: 'events',
  117. eventTypes: 'error',
  118. project: 'project-slug',
  119. },
  120. })
  121. );
  122. });
  123. });
  124. describe('Issue Alert', function () {
  125. it('loads default values', async function () {
  126. createWrapper();
  127. expect(await screen.findByText('All Environments')).toBeInTheDocument();
  128. expect(await screen.findByText('any')).toBeInTheDocument();
  129. expect(await screen.findByText('all')).toBeInTheDocument();
  130. expect(await screen.findByText('24 hours')).toBeInTheDocument();
  131. });
  132. it('can remove filters', async function () {
  133. createWrapper();
  134. const mock = MockApiClient.addMockResponse({
  135. url: '/projects/org-slug/project-slug/rules/',
  136. method: 'POST',
  137. body: TestStubs.ProjectAlertRule(),
  138. });
  139. // Change name of alert rule
  140. await userEvent.type(screen.getByPlaceholderText('Enter Alert Name'), 'myname');
  141. // Add a filter and remove it
  142. await selectEvent.select(screen.getByText('Add optional filter...'), [
  143. 'The issue is older or newer than...',
  144. ]);
  145. await userEvent.click(screen.getAllByLabelText('Delete Node')[1]);
  146. await userEvent.click(screen.getByText('Save Rule'));
  147. await waitFor(() => {
  148. expect(mock).toHaveBeenCalledWith(
  149. expect.any(String),
  150. expect.objectContaining({
  151. data: {
  152. actionMatch: 'any',
  153. actions: [],
  154. conditions: [
  155. expect.objectContaining({
  156. id: 'sentry.rules.conditions.first_seen_event.FirstSeenEventCondition',
  157. }),
  158. ],
  159. filterMatch: 'all',
  160. filters: [],
  161. frequency: 60 * 24,
  162. name: 'myname',
  163. owner: null,
  164. },
  165. })
  166. );
  167. });
  168. });
  169. it('can remove triggers', async function () {
  170. const {organization} = createWrapper();
  171. const mock = MockApiClient.addMockResponse({
  172. url: '/projects/org-slug/project-slug/rules/',
  173. method: 'POST',
  174. body: TestStubs.ProjectAlertRule(),
  175. });
  176. // delete node
  177. await userEvent.click(screen.getByLabelText('Delete Node'));
  178. // Change name of alert rule
  179. await userEvent.type(screen.getByPlaceholderText('Enter Alert Name'), 'myname');
  180. // Add a trigger and remove it
  181. await selectEvent.select(screen.getByText('Add optional trigger...'), [
  182. 'A new issue is created',
  183. ]);
  184. await userEvent.click(screen.getByLabelText('Delete Node'));
  185. await waitFor(() => {
  186. expect(trackAnalytics).toHaveBeenCalledWith('edit_alert_rule.add_row', {
  187. name: 'sentry.rules.conditions.first_seen_event.FirstSeenEventCondition',
  188. organization,
  189. project_id: '2',
  190. type: 'conditions',
  191. });
  192. });
  193. await userEvent.click(screen.getByText('Save Rule'));
  194. await waitFor(() => {
  195. expect(mock).toHaveBeenCalledWith(
  196. expect.any(String),
  197. expect.objectContaining({
  198. data: {
  199. actionMatch: 'any',
  200. actions: [],
  201. conditions: [],
  202. filterMatch: 'all',
  203. filters: [],
  204. frequency: 60 * 24,
  205. name: 'myname',
  206. owner: null,
  207. },
  208. })
  209. );
  210. });
  211. });
  212. it('can remove actions', async function () {
  213. createWrapper();
  214. const mock = MockApiClient.addMockResponse({
  215. url: '/projects/org-slug/project-slug/rules/',
  216. method: 'POST',
  217. body: TestStubs.ProjectAlertRule(),
  218. });
  219. // Change name of alert rule
  220. await userEvent.type(screen.getByPlaceholderText('Enter Alert Name'), 'myname');
  221. // Add an action and remove it
  222. await selectEvent.select(screen.getByText('Add action...'), [
  223. 'Send a notification to all legacy integrations',
  224. ]);
  225. await userEvent.click(screen.getAllByLabelText('Delete Node')[1]);
  226. await userEvent.click(screen.getByText('Save Rule'));
  227. await waitFor(() => {
  228. expect(mock).toHaveBeenCalledWith(
  229. expect.any(String),
  230. expect.objectContaining({
  231. data: {
  232. actionMatch: 'any',
  233. actions: [],
  234. conditions: [
  235. expect.objectContaining({
  236. id: 'sentry.rules.conditions.first_seen_event.FirstSeenEventCondition',
  237. }),
  238. ],
  239. filterMatch: 'all',
  240. filters: [],
  241. frequency: 60 * 24,
  242. name: 'myname',
  243. owner: null,
  244. },
  245. })
  246. );
  247. });
  248. });
  249. describe('updates and saves', function () {
  250. let mock;
  251. beforeEach(function () {
  252. mock = MockApiClient.addMockResponse({
  253. url: '/projects/org-slug/project-slug/rules/',
  254. method: 'POST',
  255. body: TestStubs.ProjectAlertRule(),
  256. });
  257. });
  258. afterEach(function () {
  259. jest.clearAllMocks();
  260. });
  261. it('environment, async action and filter match', async function () {
  262. const wrapper = createWrapper();
  263. // Change target environment
  264. await selectEvent.select(screen.getByText('All Environments'), ['production']);
  265. // Change actionMatch and filterMatch dropdown
  266. const anyDropdown = screen.getByText('any');
  267. expect(anyDropdown).toBeInTheDocument();
  268. const allDropdown = screen.getByText('all');
  269. expect(allDropdown).toBeInTheDocument();
  270. await selectEvent.select(anyDropdown, ['all']);
  271. await selectEvent.select(allDropdown, ['any']);
  272. // Change name of alert rule
  273. await userEvent.type(screen.getByPlaceholderText('Enter Alert Name'), 'myname');
  274. await userEvent.click(screen.getByText('Save Rule'));
  275. expect(mock).toHaveBeenCalledWith(
  276. expect.any(String),
  277. expect.objectContaining({
  278. data: {
  279. actionMatch: 'all',
  280. filterMatch: 'any',
  281. conditions: [
  282. expect.objectContaining({
  283. id: 'sentry.rules.conditions.first_seen_event.FirstSeenEventCondition',
  284. }),
  285. ],
  286. actions: [],
  287. filters: [],
  288. environment: 'production',
  289. frequency: 60 * 24,
  290. name: 'myname',
  291. owner: null,
  292. },
  293. })
  294. );
  295. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  296. await waitFor(() => {
  297. expect(wrapper.router.push).toHaveBeenCalledWith({
  298. pathname: '/organizations/org-slug/alerts/rules/project-slug/1/details/',
  299. });
  300. });
  301. });
  302. it('new condition', async function () {
  303. const wrapper = createWrapper();
  304. // Change name of alert rule
  305. await userEvent.click(screen.getByPlaceholderText('Enter Alert Name'));
  306. await userEvent.paste('myname');
  307. // Add another condition
  308. await selectEvent.select(screen.getByText('Add optional filter...'), [
  309. "The event's tags match {key} {match} {value}",
  310. ]);
  311. // Edit new Condition
  312. await userEvent.click(screen.getByPlaceholderText('key'));
  313. await userEvent.paste('conditionKey');
  314. await userEvent.click(screen.getByPlaceholderText('value'));
  315. await userEvent.paste('conditionValue');
  316. await selectEvent.select(screen.getByText('contains'), ['does not equal']);
  317. await userEvent.click(screen.getByText('Save Rule'));
  318. expect(mock).toHaveBeenCalledWith(
  319. expect.any(String),
  320. expect.objectContaining({
  321. data: {
  322. actionMatch: 'any',
  323. actions: [],
  324. conditions: [
  325. expect.objectContaining({
  326. id: 'sentry.rules.conditions.first_seen_event.FirstSeenEventCondition',
  327. }),
  328. ],
  329. filterMatch: 'all',
  330. filters: [
  331. {
  332. id: 'sentry.rules.filters.tagged_event.TaggedEventFilter',
  333. key: 'conditionKey',
  334. match: 'ne',
  335. value: 'conditionValue',
  336. },
  337. ],
  338. frequency: 60 * 24,
  339. name: 'myname',
  340. owner: null,
  341. },
  342. })
  343. );
  344. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  345. await waitFor(() => {
  346. expect(wrapper.router.push).toHaveBeenCalledWith({
  347. pathname: '/organizations/org-slug/alerts/rules/project-slug/1/details/',
  348. });
  349. });
  350. });
  351. it('new filter', async function () {
  352. const wrapper = createWrapper();
  353. // Change name of alert rule
  354. await userEvent.click(screen.getByPlaceholderText('Enter Alert Name'));
  355. await userEvent.paste('myname');
  356. // delete one condition
  357. await userEvent.click(screen.getAllByLabelText('Delete Node')[0]);
  358. // Add a new filter
  359. await selectEvent.select(screen.getByText('Add optional filter...'), [
  360. 'The issue is older or newer than...',
  361. ]);
  362. await userEvent.click(screen.getByPlaceholderText('10'));
  363. await userEvent.paste('12');
  364. await userEvent.click(screen.getByText('Save Rule'));
  365. expect(mock).toHaveBeenCalledWith(
  366. expect.any(String),
  367. expect.objectContaining({
  368. data: {
  369. actionMatch: 'any',
  370. filterMatch: 'all',
  371. filters: [
  372. {
  373. id: 'sentry.rules.filters.age_comparison.AgeComparisonFilter',
  374. comparison_type: 'older',
  375. time: 'minute',
  376. value: '12',
  377. },
  378. ],
  379. actions: [],
  380. conditions: [],
  381. frequency: 60 * 24,
  382. name: 'myname',
  383. owner: null,
  384. },
  385. })
  386. );
  387. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  388. await waitFor(() => {
  389. expect(wrapper.router.push).toHaveBeenCalledWith({
  390. pathname: '/organizations/org-slug/alerts/rules/project-slug/1/details/',
  391. });
  392. });
  393. });
  394. it('new action', async function () {
  395. const wrapper = createWrapper();
  396. // Change name of alert rule
  397. await userEvent.type(screen.getByPlaceholderText('Enter Alert Name'), 'myname');
  398. // Add a new action
  399. await selectEvent.select(screen.getByText('Add action...'), [
  400. 'Issue Owners, Team, or Member',
  401. ]);
  402. // Update action interval
  403. await selectEvent.select(screen.getByText('24 hours'), ['60 minutes']);
  404. await userEvent.click(screen.getByText('Save Rule'));
  405. expect(mock).toHaveBeenCalledWith(
  406. expect.any(String),
  407. expect.objectContaining({
  408. data: {
  409. actionMatch: 'any',
  410. actions: [
  411. {id: 'sentry.mail.actions.NotifyEmailAction', targetType: 'IssueOwners'},
  412. ],
  413. conditions: [
  414. expect.objectContaining({
  415. id: 'sentry.rules.conditions.first_seen_event.FirstSeenEventCondition',
  416. }),
  417. ],
  418. filterMatch: 'all',
  419. filters: [],
  420. frequency: '60',
  421. name: 'myname',
  422. owner: null,
  423. },
  424. })
  425. );
  426. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  427. await waitFor(() => {
  428. expect(wrapper.router.push).toHaveBeenCalledWith({
  429. pathname: '/organizations/org-slug/alerts/rules/project-slug/1/details/',
  430. });
  431. });
  432. });
  433. });
  434. });
  435. describe('test preview chart', () => {
  436. it('valid preview table', async () => {
  437. const groups = TestStubs.Groups();
  438. const date = new Date();
  439. for (let i = 0; i < groups.length; i++) {
  440. groups[i].lastTriggered = date;
  441. }
  442. const mock = MockApiClient.addMockResponse({
  443. url: '/projects/org-slug/project-slug/rules/preview/',
  444. method: 'POST',
  445. body: groups,
  446. headers: {
  447. 'X-Hits': groups.length,
  448. Endpoint: 'endpoint',
  449. },
  450. });
  451. createWrapper();
  452. await waitFor(() => {
  453. expect(mock).toHaveBeenCalledWith(
  454. expect.any(String),
  455. expect.objectContaining({
  456. data: {
  457. actionMatch: 'any',
  458. conditions: [
  459. expect.objectContaining({
  460. id: 'sentry.rules.conditions.first_seen_event.FirstSeenEventCondition',
  461. }),
  462. ],
  463. filterMatch: 'all',
  464. filters: [],
  465. frequency: 60 * 24,
  466. endpoint: null,
  467. },
  468. })
  469. );
  470. });
  471. expect(
  472. screen.getByText('4 issues would have triggered this rule in the past 14 days', {
  473. exact: false,
  474. })
  475. ).toBeInTheDocument();
  476. for (const group of groups) {
  477. expect(screen.getByText(group.shortId)).toBeInTheDocument();
  478. }
  479. expect(screen.getAllByText('3mo ago')[0]).toBeInTheDocument();
  480. });
  481. it('invalid preview alert', async () => {
  482. const mock = MockApiClient.addMockResponse({
  483. url: '/projects/org-slug/project-slug/rules/preview/',
  484. method: 'POST',
  485. statusCode: 400,
  486. });
  487. createWrapper();
  488. // delete existion condition
  489. await userEvent.click(screen.getAllByLabelText('Delete Node')[0]);
  490. await waitFor(() => {
  491. expect(mock).toHaveBeenCalled();
  492. });
  493. expect(
  494. screen.getByText('Select a condition to generate a preview')
  495. ).toBeInTheDocument();
  496. await selectEvent.select(screen.getByText('Add optional trigger...'), [
  497. 'A new issue is created',
  498. ]);
  499. expect(
  500. screen.getByText('Preview is not supported for these conditions')
  501. ).toBeInTheDocument();
  502. });
  503. it('empty preview table', async () => {
  504. const mock = MockApiClient.addMockResponse({
  505. url: '/projects/org-slug/project-slug/rules/preview/',
  506. method: 'POST',
  507. body: [],
  508. headers: {
  509. 'X-Hits': '0',
  510. Endpoint: 'endpoint',
  511. },
  512. });
  513. createWrapper();
  514. await waitFor(() => {
  515. expect(mock).toHaveBeenCalled();
  516. });
  517. expect(
  518. screen.getByText("We couldn't find any issues that would've triggered your rule")
  519. ).toBeInTheDocument();
  520. });
  521. });
  522. describe('test incompatible conditions', () => {
  523. const errorText =
  524. 'The conditions highlighted in red are in conflict. They may prevent the alert from ever being triggered.';
  525. it('shows error for incompatible conditions', async () => {
  526. createWrapper();
  527. const anyDropdown = screen.getByText('any');
  528. expect(anyDropdown).toBeInTheDocument();
  529. await selectEvent.select(anyDropdown, ['all']);
  530. await selectEvent.select(screen.getByText('Add optional trigger...'), [
  531. 'The issue changes state from resolved to unresolved',
  532. ]);
  533. expect(screen.getByText(errorText)).toBeInTheDocument();
  534. expect(screen.getByRole('button', {name: 'Save Rule'})).toHaveAttribute(
  535. 'aria-disabled',
  536. 'true'
  537. );
  538. await userEvent.click(screen.getAllByLabelText('Delete Node')[0]);
  539. expect(screen.queryByText(errorText)).not.toBeInTheDocument();
  540. });
  541. it('test any filterMatch', async () => {
  542. createWrapper();
  543. const allDropdown = screen.getByText('all');
  544. await selectEvent.select(allDropdown, ['any']);
  545. await selectEvent.select(screen.getByText('Add optional filter...'), [
  546. 'The issue is older or newer than...',
  547. ]);
  548. await userEvent.type(screen.getByPlaceholderText('10'), '10');
  549. await userEvent.click(document.body);
  550. await selectEvent.select(screen.getByText('Add optional filter...'), [
  551. 'The issue has happened at least {x} times (Note: this is approximate)',
  552. ]);
  553. expect(screen.getByText(errorText)).toBeInTheDocument();
  554. await userEvent.click(screen.getAllByLabelText('Delete Node')[1]);
  555. await userEvent.clear(screen.getByDisplayValue('10'));
  556. await userEvent.click(document.body);
  557. expect(screen.queryByText(errorText)).not.toBeInTheDocument();
  558. });
  559. });
  560. it('shows archived to escalating instead of ignored to unresolved', async () => {
  561. createWrapper({
  562. organization: TestStubs.Organization({features: ['escalating-issues']}),
  563. });
  564. await selectEvent.select(screen.getByText('Add optional trigger...'), [
  565. 'The issue changes state from archived to escalating',
  566. ]);
  567. expect(
  568. screen.getByText('The issue changes state from archived to escalating')
  569. ).toBeInTheDocument();
  570. });
  571. });