create.spec.jsx 19 KB

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