create.spec.jsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. import selectEvent from 'react-select-event';
  2. import moment from 'moment';
  3. import {initializeOrg} from 'sentry-test/initializeOrg';
  4. import {act, render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
  5. import ProjectsStore from 'sentry/stores/projectsStore';
  6. import TeamStore from 'sentry/stores/teamStore';
  7. import {metric} from 'sentry/utils/analytics';
  8. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  9. import AlertsContainer from 'sentry/views/alerts';
  10. import AlertBuilderProjectProvider from 'sentry/views/alerts/builder/projectProvider';
  11. import ProjectAlertsCreate from 'sentry/views/alerts/create';
  12. jest.unmock('sentry/utils/recreateRoute');
  13. jest.mock('sentry/actionCreators/members');
  14. jest.mock('react-router');
  15. jest.mock('sentry/utils/analytics', () => ({
  16. metric: {
  17. startTransaction: jest.fn(() => ({
  18. setTag: jest.fn(),
  19. setData: jest.fn(),
  20. })),
  21. endTransaction: jest.fn(),
  22. mark: jest.fn(),
  23. measure: jest.fn(),
  24. },
  25. trackAdvancedAnalyticsEvent: jest.fn(),
  26. }));
  27. jest.mock('sentry/utils/analytics/trackAdvancedAnalyticsEvent');
  28. describe('ProjectAlertsCreate', function () {
  29. beforeEach(function () {
  30. TeamStore.init();
  31. TeamStore.loadInitialData([], false, null);
  32. MockApiClient.addMockResponse({
  33. url: '/projects/org-slug/project-slug/rules/configuration/',
  34. body: TestStubs.ProjectAlertRuleConfiguration(),
  35. });
  36. MockApiClient.addMockResponse({
  37. url: '/projects/org-slug/project-slug/rules/1/',
  38. body: TestStubs.ProjectAlertRule(),
  39. });
  40. MockApiClient.addMockResponse({
  41. url: '/projects/org-slug/project-slug/environments/',
  42. body: TestStubs.Environments(),
  43. });
  44. MockApiClient.addMockResponse({
  45. url: `/projects/org-slug/project-slug/?expand=hasAlertIntegration`,
  46. body: {},
  47. });
  48. MockApiClient.addMockResponse({
  49. url: `/projects/org-slug/project-slug/ownership/`,
  50. method: 'GET',
  51. body: {
  52. fallthrough: false,
  53. autoAssignment: false,
  54. },
  55. });
  56. });
  57. afterEach(function () {
  58. MockApiClient.clearMockResponses();
  59. jest.clearAllMocks();
  60. });
  61. const createWrapper = (props = {}, location = {}) => {
  62. const {organization, project, router} = initializeOrg(props);
  63. ProjectsStore.loadInitialData([project]);
  64. const params = {orgId: organization.slug, projectId: project.slug};
  65. const wrapper = render(
  66. <AlertsContainer>
  67. <AlertBuilderProjectProvider params={params}>
  68. <ProjectAlertsCreate
  69. params={params}
  70. location={{
  71. pathname: `/organizations/org-slug/alerts/rules/${project.slug}/new/`,
  72. query: {createFromWizard: true},
  73. ...location,
  74. }}
  75. router={router}
  76. />
  77. </AlertBuilderProjectProvider>
  78. </AlertsContainer>,
  79. {organization}
  80. );
  81. return {
  82. wrapper,
  83. organization,
  84. project,
  85. router,
  86. };
  87. };
  88. it('adds default parameters if wizard was skipped', function () {
  89. const location = {query: {}};
  90. const wrapper = createWrapper(undefined, location);
  91. expect(wrapper.router.replace).toHaveBeenCalledWith({
  92. pathname: '/organizations/org-slug/alerts/new/metric',
  93. query: {
  94. aggregate: 'count()',
  95. dataset: 'events',
  96. eventTypes: 'error',
  97. project: 'project-slug',
  98. },
  99. });
  100. });
  101. describe('Issue Alert', function () {
  102. it('loads default values', function () {
  103. createWrapper();
  104. expect(screen.getByText('All Environments')).toBeInTheDocument();
  105. expect(screen.getAllByDisplayValue('all')).toHaveLength(2);
  106. expect(screen.getByText('30 minutes')).toBeInTheDocument();
  107. });
  108. it('can remove filters', async function () {
  109. createWrapper();
  110. const mock = MockApiClient.addMockResponse({
  111. url: '/projects/org-slug/project-slug/rules/',
  112. method: 'POST',
  113. body: TestStubs.ProjectAlertRule(),
  114. });
  115. // Change name of alert rule
  116. userEvent.paste(screen.getByPlaceholderText('Enter Alert Name'), 'My Rule Name');
  117. // Add a filter and remove it
  118. await selectEvent.select(screen.getByText('Add optional filter...'), [
  119. 'The issue is older or newer than...',
  120. ]);
  121. userEvent.click(screen.getByLabelText('Delete Node'));
  122. userEvent.click(screen.getByText('Save Rule'));
  123. expect(mock).toHaveBeenCalledWith(
  124. expect.any(String),
  125. expect.objectContaining({
  126. data: {
  127. actionMatch: 'all',
  128. actions: [],
  129. conditions: [],
  130. filterMatch: 'all',
  131. filters: [],
  132. frequency: 30,
  133. name: 'My Rule Name',
  134. owner: null,
  135. },
  136. })
  137. );
  138. // updateOnboardingTask triggers an out of band state update
  139. await act(tick);
  140. });
  141. it('can remove triggers', async function () {
  142. const {organization} = createWrapper();
  143. const mock = MockApiClient.addMockResponse({
  144. url: '/projects/org-slug/project-slug/rules/',
  145. method: 'POST',
  146. body: TestStubs.ProjectAlertRule(),
  147. });
  148. // Change name of alert rule
  149. userEvent.paste(screen.getByPlaceholderText('Enter Alert Name'), 'My Rule Name');
  150. // Add a trigger and remove it
  151. await selectEvent.select(screen.getByText('Add optional trigger...'), [
  152. 'A new issue is created',
  153. ]);
  154. userEvent.click(screen.getByLabelText('Delete Node'));
  155. expect(trackAdvancedAnalyticsEvent).toHaveBeenCalledWith(
  156. 'edit_alert_rule.add_row',
  157. {
  158. name: 'sentry.rules.conditions.first_seen_event.FirstSeenEventCondition',
  159. organization,
  160. project_id: '2',
  161. type: 'conditions',
  162. }
  163. );
  164. userEvent.click(screen.getByText('Save Rule'));
  165. expect(mock).toHaveBeenCalledWith(
  166. expect.any(String),
  167. expect.objectContaining({
  168. data: {
  169. actionMatch: 'all',
  170. actions: [],
  171. conditions: [],
  172. filterMatch: 'all',
  173. filters: [],
  174. frequency: 30,
  175. name: 'My Rule Name',
  176. owner: null,
  177. },
  178. })
  179. );
  180. // updateOnboardingTask triggers an out of band state update
  181. await act(tick);
  182. });
  183. it('can remove actions', async function () {
  184. createWrapper();
  185. const mock = MockApiClient.addMockResponse({
  186. url: '/projects/org-slug/project-slug/rules/',
  187. method: 'POST',
  188. body: TestStubs.ProjectAlertRule(),
  189. });
  190. // Change name of alert rule
  191. userEvent.paste(screen.getByPlaceholderText('Enter Alert Name'), 'My Rule Name');
  192. // Add an action and remove it
  193. await selectEvent.select(screen.getByText('Add action...'), [
  194. 'Send a notification to all legacy integrations',
  195. ]);
  196. userEvent.click(screen.getByLabelText('Delete Node'));
  197. userEvent.click(screen.getByText('Save Rule'));
  198. expect(mock).toHaveBeenCalledWith(
  199. expect.any(String),
  200. expect.objectContaining({
  201. data: {
  202. actionMatch: 'all',
  203. actions: [],
  204. conditions: [],
  205. filterMatch: 'all',
  206. filters: [],
  207. frequency: 30,
  208. name: 'My Rule Name',
  209. owner: null,
  210. },
  211. })
  212. );
  213. // updateOnboardingTask triggers an out of band state update
  214. await act(tick);
  215. });
  216. describe('updates and saves', function () {
  217. let mock;
  218. beforeEach(function () {
  219. mock = MockApiClient.addMockResponse({
  220. url: '/projects/org-slug/project-slug/rules/',
  221. method: 'POST',
  222. body: TestStubs.ProjectAlertRule(),
  223. });
  224. });
  225. afterEach(function () {
  226. jest.clearAllMocks();
  227. });
  228. it('environment, action and filter match', async function () {
  229. const wrapper = createWrapper();
  230. // Change target environment
  231. await selectEvent.select(screen.getByText('All Environments'), ['production']);
  232. // Change actionMatch and filterMatch dropdown
  233. const allDropdowns = screen.getAllByText('all');
  234. expect(allDropdowns).toHaveLength(2);
  235. await selectEvent.select(allDropdowns[0], ['any']);
  236. await selectEvent.select(allDropdowns[1], ['any']);
  237. // Change name of alert rule
  238. userEvent.paste(screen.getByPlaceholderText('Enter Alert Name'), 'My Rule Name');
  239. userEvent.click(screen.getByText('Save Rule'));
  240. expect(mock).toHaveBeenCalledWith(
  241. expect.any(String),
  242. expect.objectContaining({
  243. data: {
  244. actionMatch: 'any',
  245. filterMatch: 'any',
  246. conditions: [],
  247. actions: [],
  248. filters: [],
  249. environment: 'production',
  250. frequency: 30,
  251. name: 'My Rule Name',
  252. owner: null,
  253. },
  254. })
  255. );
  256. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  257. await waitFor(() => {
  258. expect(wrapper.router.push).toHaveBeenCalledWith({
  259. pathname: '/organizations/org-slug/alerts/rules/project-slug/1/details/',
  260. });
  261. });
  262. });
  263. it('new condition', async function () {
  264. const wrapper = createWrapper();
  265. // Change name of alert rule
  266. userEvent.paste(screen.getByPlaceholderText('Enter Alert Name'), 'My Rule Name');
  267. // Add another condition
  268. await selectEvent.select(screen.getByText('Add optional filter...'), [
  269. "The event's tags match {key} {match} {value}",
  270. ]);
  271. // Edit new Condition
  272. userEvent.paste(screen.getByPlaceholderText('key'), 'conditionKey');
  273. userEvent.paste(screen.getByPlaceholderText('value'), 'conditionValue');
  274. await selectEvent.select(screen.getByText('contains'), ['does not equal']);
  275. userEvent.click(screen.getByText('Save Rule'));
  276. expect(mock).toHaveBeenCalledWith(
  277. expect.any(String),
  278. expect.objectContaining({
  279. data: {
  280. actionMatch: 'all',
  281. actions: [],
  282. conditions: [],
  283. filterMatch: 'all',
  284. filters: [
  285. {
  286. id: 'sentry.rules.filters.tagged_event.TaggedEventFilter',
  287. key: 'conditionKey',
  288. match: 'ne',
  289. value: 'conditionValue',
  290. },
  291. ],
  292. frequency: 30,
  293. name: 'My Rule Name',
  294. owner: null,
  295. },
  296. })
  297. );
  298. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  299. await waitFor(() => {
  300. expect(wrapper.router.push).toHaveBeenCalledWith({
  301. pathname: '/organizations/org-slug/alerts/rules/project-slug/1/details/',
  302. });
  303. });
  304. });
  305. it('new filter', async function () {
  306. const wrapper = createWrapper();
  307. // Change name of alert rule
  308. userEvent.paste(screen.getByPlaceholderText('Enter Alert Name'), 'My Rule Name');
  309. // Add a new filter
  310. await selectEvent.select(screen.getByText('Add optional filter...'), [
  311. 'The issue is older or newer than...',
  312. ]);
  313. userEvent.paste(screen.getByPlaceholderText('10'), '12');
  314. userEvent.click(screen.getByText('Save Rule'));
  315. expect(mock).toHaveBeenCalledWith(
  316. expect.any(String),
  317. expect.objectContaining({
  318. data: {
  319. actionMatch: 'all',
  320. filterMatch: 'all',
  321. filters: [
  322. {
  323. id: 'sentry.rules.filters.age_comparison.AgeComparisonFilter',
  324. comparison_type: 'older',
  325. time: 'minute',
  326. value: '12',
  327. },
  328. ],
  329. actions: [],
  330. conditions: [],
  331. frequency: 30,
  332. name: 'My Rule Name',
  333. owner: null,
  334. },
  335. })
  336. );
  337. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  338. await waitFor(() => {
  339. expect(wrapper.router.push).toHaveBeenCalledWith({
  340. pathname: '/organizations/org-slug/alerts/rules/project-slug/1/details/',
  341. });
  342. });
  343. });
  344. it('new action', async function () {
  345. const wrapper = createWrapper();
  346. // Change name of alert rule
  347. userEvent.paste(screen.getByPlaceholderText('Enter Alert Name'), 'My Rule Name');
  348. // Add a new action
  349. await selectEvent.select(screen.getByText('Add action...'), [
  350. 'Issue Owners, Team, or Member',
  351. ]);
  352. // Update action interval
  353. await selectEvent.select(screen.getByText('30 minutes'), ['60 minutes']);
  354. userEvent.click(screen.getByText('Save Rule'));
  355. expect(mock).toHaveBeenCalledWith(
  356. expect.any(String),
  357. expect.objectContaining({
  358. data: {
  359. actionMatch: 'all',
  360. actions: [
  361. {id: 'sentry.mail.actions.NotifyEmailAction', targetType: 'IssueOwners'},
  362. ],
  363. conditions: [],
  364. filterMatch: 'all',
  365. filters: [],
  366. frequency: '60',
  367. name: 'My Rule Name',
  368. owner: null,
  369. },
  370. })
  371. );
  372. expect(metric.startTransaction).toHaveBeenCalledWith({name: 'saveAlertRule'});
  373. await waitFor(() => {
  374. expect(wrapper.router.push).toHaveBeenCalledWith({
  375. pathname: '/organizations/org-slug/alerts/rules/project-slug/1/details/',
  376. });
  377. });
  378. });
  379. });
  380. });
  381. describe('test preview chart', () => {
  382. const organization = TestStubs.Organization({features: ['issue-alert-preview']});
  383. afterEach(() => {
  384. jest.clearAllMocks();
  385. });
  386. it('generate valid preview chart', async () => {
  387. const mock = MockApiClient.addMockResponse({
  388. url: '/projects/org-slug/project-slug/rules/preview',
  389. method: 'POST',
  390. body: [
  391. {datetime: moment().subtract(2, 'days').format(), count: 1},
  392. {datetime: moment().subtract(1, 'days').format(), count: 2},
  393. {datetime: moment().format(), count: 3},
  394. ],
  395. });
  396. createWrapper({organization});
  397. userEvent.click(screen.getByText('Generate Preview'));
  398. await waitFor(() => {
  399. expect(mock).toHaveBeenCalledWith(
  400. expect.any(String),
  401. expect.objectContaining({
  402. data: {
  403. actionMatch: 'all',
  404. conditions: [],
  405. filterMatch: 'all',
  406. filters: [],
  407. frequency: 30,
  408. },
  409. })
  410. );
  411. });
  412. expect(screen.getByText('Alerts Triggered')).toBeInTheDocument();
  413. expect(screen.getByText('Total Alerts')).toBeInTheDocument();
  414. });
  415. it('invalid preview chart', async () => {
  416. const mock = MockApiClient.addMockResponse({
  417. url: '/projects/org-slug/project-slug/rules/preview',
  418. method: 'POST',
  419. statusCode: 400,
  420. });
  421. createWrapper({organization});
  422. userEvent.click(screen.getByText('Generate Preview'));
  423. await waitFor(() => {
  424. expect(mock).toHaveBeenCalled();
  425. });
  426. expect(
  427. screen.getByText(
  428. 'Previews are unavailable for this combination of conditions and filters'
  429. )
  430. ).toBeInTheDocument();
  431. });
  432. });
  433. });