geido commented on code in PR #29264:
URL: https://github.com/apache/superset/pull/29264#discussion_r1681363350


##########
superset-frontend/src/features/alerts/components/NotificationMethod.test.tsx:
##########
@@ -0,0 +1,182 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { render, screen, fireEvent } from 'spec/helpers/testing-library';
+import { NotificationMethod, mapSlackValues } from './NotificationMethod';
+import { NotificationMethodOption, NotificationSetting } from '../types';
+
+const mockOnUpdate = jest.fn();
+const mockOnRemove = jest.fn();
+const mockOnInputChange = jest.fn();
+const mockSetErrorSubject = jest.fn();
+
+const mockSetting: NotificationSetting = {
+  method: NotificationMethodOption.Email,
+  recipients: '[email protected]',
+  options: [
+    NotificationMethodOption.Email,
+    NotificationMethodOption.Slack,
+    NotificationMethodOption.SlackV2,
+  ],
+};
+
+const mockEmailSubject = 'Test Subject';
+const mockDefaultSubject = 'Default Subject';
+
+describe('NotificationMethod', () => {
+  beforeEach(() => {
+    jest.clearAllMocks();
+  });
+
+  it('should render the component', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    expect(screen.getByText('Notification Method')).toBeInTheDocument();
+    expect(
+      screen.getByText('Email subject name (optional)'),
+    ).toBeInTheDocument();
+    expect(screen.getByText('Email recipients')).toBeInTheDocument();
+  });
+
+  it('should call onRemove when the delete button is clicked', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={1}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const deleteButton = screen.getByRole('button');
+    fireEvent.click(deleteButton);
+
+    expect(mockOnRemove).toHaveBeenCalledWith(1);
+  });
+  // Should update recipient value when input changes.
+
+  it('should update recipient value when input changes', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const recipientsInput = screen.getByTestId('recipients');
+    fireEvent.change(recipientsInput, {

Review Comment:
   Can we use userEvent here instead and everywhere else?



##########
superset-frontend/src/features/alerts/components/NotificationMethod.test.tsx:
##########
@@ -0,0 +1,182 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { render, screen, fireEvent } from 'spec/helpers/testing-library';
+import { NotificationMethod, mapSlackValues } from './NotificationMethod';
+import { NotificationMethodOption, NotificationSetting } from '../types';
+
+const mockOnUpdate = jest.fn();
+const mockOnRemove = jest.fn();
+const mockOnInputChange = jest.fn();
+const mockSetErrorSubject = jest.fn();
+
+const mockSetting: NotificationSetting = {
+  method: NotificationMethodOption.Email,
+  recipients: '[email protected]',
+  options: [
+    NotificationMethodOption.Email,
+    NotificationMethodOption.Slack,
+    NotificationMethodOption.SlackV2,
+  ],
+};
+
+const mockEmailSubject = 'Test Subject';
+const mockDefaultSubject = 'Default Subject';
+
+describe('NotificationMethod', () => {
+  beforeEach(() => {
+    jest.clearAllMocks();
+  });
+
+  it('should render the component', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    expect(screen.getByText('Notification Method')).toBeInTheDocument();
+    expect(
+      screen.getByText('Email subject name (optional)'),
+    ).toBeInTheDocument();
+    expect(screen.getByText('Email recipients')).toBeInTheDocument();
+  });
+
+  it('should call onRemove when the delete button is clicked', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={1}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const deleteButton = screen.getByRole('button');
+    fireEvent.click(deleteButton);
+
+    expect(mockOnRemove).toHaveBeenCalledWith(1);
+  });
+  // Should update recipient value when input changes.

Review Comment:
   ```suggestion
   ```



##########
superset-frontend/src/features/alerts/components/NotificationMethod.test.tsx:
##########
@@ -0,0 +1,182 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { render, screen, fireEvent } from 'spec/helpers/testing-library';
+import { NotificationMethod, mapSlackValues } from './NotificationMethod';
+import { NotificationMethodOption, NotificationSetting } from '../types';
+
+const mockOnUpdate = jest.fn();
+const mockOnRemove = jest.fn();
+const mockOnInputChange = jest.fn();
+const mockSetErrorSubject = jest.fn();
+
+const mockSetting: NotificationSetting = {
+  method: NotificationMethodOption.Email,
+  recipients: '[email protected]',
+  options: [
+    NotificationMethodOption.Email,
+    NotificationMethodOption.Slack,
+    NotificationMethodOption.SlackV2,
+  ],
+};
+
+const mockEmailSubject = 'Test Subject';
+const mockDefaultSubject = 'Default Subject';
+
+describe('NotificationMethod', () => {
+  beforeEach(() => {
+    jest.clearAllMocks();
+  });
+
+  it('should render the component', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    expect(screen.getByText('Notification Method')).toBeInTheDocument();
+    expect(
+      screen.getByText('Email subject name (optional)'),
+    ).toBeInTheDocument();
+    expect(screen.getByText('Email recipients')).toBeInTheDocument();
+  });
+
+  it('should call onRemove when the delete button is clicked', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={1}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const deleteButton = screen.getByRole('button');
+    fireEvent.click(deleteButton);
+
+    expect(mockOnRemove).toHaveBeenCalledWith(1);
+  });
+  // Should update recipient value when input changes.
+
+  it('should update recipient value when input changes', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const recipientsInput = screen.getByTestId('recipients');
+    fireEvent.change(recipientsInput, {
+      target: { value: '[email protected]' },
+    });
+
+    expect(mockOnUpdate).toHaveBeenCalledWith(0, {
+      ...mockSetting,
+      recipients: '[email protected]',
+    });
+  });
+
+  it('should call onRecipientsChange when the recipients value is changed', () 
=> {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const recipientsInput = screen.getByTestId('recipients');
+    fireEvent.change(recipientsInput, {
+      target: { value: '[email protected]' },
+    });
+
+    expect(mockOnUpdate).toHaveBeenCalledWith(0, {
+      ...mockSetting,
+      recipients: '[email protected]',
+    });
+  });
+  // correctly maps recipients when method is SlackV2

Review Comment:
   ```suggestion
   ```



##########
superset-frontend/src/features/alerts/components/NotificationMethod.tsx:
##########
@@ -87,27 +168,125 @@ export const NotificationMethod: 
FunctionComponent<NotificationMethodProps> = ({
   const [recipientValue, setRecipientValue] = useState<string>(
     recipients || '',
   );
+  const [slackRecipients, setSlackRecipients] = useState<
+    { label: string; value: string }[]
+  >([]);
   const [error, setError] = useState(false);
   const theme = useTheme();
+  const [slackOptions, setSlackOptions] = useState<SlackOptionsType>([
+    {
+      label: '',
+      options: [],
+    },
+  ]);
 
-  if (!setting) {
-    return null;
-  }
+  const [useSlackV1, setUseSlackV1] = useState<boolean>(false);
 
-  const onMethodChange = (method: NotificationMethodOption) => {
+  const onMethodChange = (selected: {
+    label: string;
+    value: NotificationMethodOption;
+  }) => {
     // Since we're swapping the method, reset the recipients
     setRecipientValue('');
-    if (onUpdate) {
+    if (onUpdate && setting) {
       const updatedSetting = {
         ...setting,
-        method,
+        method: selected.value,
         recipients: '',
       };
 
       onUpdate(index, updatedSetting);
     }
   };
 
+  const fetchSlackChannels = async ({
+    searchString = '',
+    types = [],
+    exactMatch = false,
+  }: {
+    searchString?: string | undefined;
+    types?: string[];
+    exactMatch?: boolean | undefined;
+  } = {}): Promise<JsonResponse> => {
+    const queryString = rison.encode({ searchString, types, exactMatch });
+    const endpoint = `/api/v1/report/slack_channels/?q=${queryString}`;
+    return SupersetClient.get({ endpoint });
+  };
+
+  useEffect(() => {
+    if (
+      method &&
+      [
+        NotificationMethodOption.Slack,
+        NotificationMethodOption.SlackV2,
+      ].includes(method) &&
+      !slackOptions[0].options.length

Review Comment:
   ```suggestion
         !slackOptions[0]?.options.length
   ```



##########
superset-frontend/src/features/alerts/components/NotificationMethod.tsx:
##########
@@ -73,6 +92,68 @@ const TRANSLATIONS = {
   ),
 };
 
+export const mapSlackValues = ({
+  method,
+  recipientValue,
+  slackOptions,
+}: {
+  method: string;
+  recipientValue: string;
+  slackOptions: { label: string; value: string }[];
+}) => {
+  const prop = method === NotificationMethodOption.SlackV2 ? 'value' : 'label';
+  return recipientValue
+    .split(',')
+    .map(recipient =>
+      slackOptions.find(
+        option =>
+          option[prop].trim().toLowerCase() === recipient.trim().toLowerCase(),
+      ),
+    )
+    .filter(val => !!val) as { label: string; value: string }[];
+};
+
+export const mapChannelsToOptions = (result: SlackChannel[]) => {
+  const publicChannels: SlackChannel[] = [];
+  const privateChannels: SlackChannel[] = [];
+
+  result.forEach(channel => {
+    if (channel.is_private) {
+      privateChannels.push(channel);
+    } else {
+      publicChannels.push(channel);
+    }
+  });
+
+  return [
+    {
+      label: 'Public Channels',
+      options: publicChannels.map((channel: SlackChannel) => ({
+        label: `${channel.name} ${
+          channel.is_member ? '' : '(Bot not in channel)'

Review Comment:
   This might need to be localized



##########
superset/reports/api.py:
##########
@@ -513,3 +517,68 @@ def bulk_delete(self, **kwargs: Any) -> Response:
             return self.response_403()
         except ReportScheduleDeleteFailedError as ex:
             return self.response_422(message=str(ex))
+
+    @expose("/slack_channels/", methods=("GET",))
+    @protect()
+    @rison(get_slack_channels_schema)
+    @safe
+    @statsd_metrics
+    @event_logger.log_this_with_context(
+        action=lambda self,
+        *args,
+        **kwargs: f"{self.__class__.__name__}.slack_channels",
+        log_to_statsd=False,
+    )
+    def slack_channels(self, **kwargs: Any) -> Response:
+        """Get slack channels.
+        ---
+        get:
+          summary: Get slack channels
+          description: Get slack channels
+          parameters:
+            - in: query
+              name: q
+              content:
+                application/json:
+                  schema:
+                    $ref: '#/components/schemas/get_slack_channels_schema'
+          responses:
+            200:
+              description: Slack channels
+              content:
+                application/json:
+                  schema:
+                    type: object
+                    properties:
+                      result:
+                        type: array
+                        items:
+                          type: object
+                          properties:
+                            id:
+                              type: string
+                            name:
+                              type: string
+            401:
+              $ref: '#/components/responses/401'
+            403:
+              $ref: '#/components/responses/403'
+            404:
+              $ref: '#/components/responses/404'
+            422:
+              $ref: '#/components/responses/422'
+            500:
+              $ref: '#/components/responses/500'
+        """
+        try:
+            params = kwargs.get("rison", {})
+            search_string = params.get("search_string")
+            types = params.get("types", [])
+            exact_match = params.get("exact_match", False)
+            channels = get_channels_with_search(
+                search_string=search_string, types=types, 
exact_match=exact_match
+            )
+            return self.response(200, result=channels)
+        except SupersetException as ex:
+            logger.error("Error fetching slack channels %s", str(ex))
+            return self.response_422(message=str(ex))

Review Comment:
   Do we want to expose the original error message here?



##########
superset-frontend/src/features/alerts/components/NotificationMethod.test.tsx:
##########
@@ -0,0 +1,182 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { render, screen, fireEvent } from 'spec/helpers/testing-library';
+import { NotificationMethod, mapSlackValues } from './NotificationMethod';
+import { NotificationMethodOption, NotificationSetting } from '../types';
+
+const mockOnUpdate = jest.fn();
+const mockOnRemove = jest.fn();
+const mockOnInputChange = jest.fn();
+const mockSetErrorSubject = jest.fn();
+
+const mockSetting: NotificationSetting = {
+  method: NotificationMethodOption.Email,
+  recipients: '[email protected]',
+  options: [
+    NotificationMethodOption.Email,
+    NotificationMethodOption.Slack,
+    NotificationMethodOption.SlackV2,
+  ],
+};
+
+const mockEmailSubject = 'Test Subject';
+const mockDefaultSubject = 'Default Subject';
+
+describe('NotificationMethod', () => {
+  beforeEach(() => {
+    jest.clearAllMocks();
+  });
+
+  it('should render the component', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    expect(screen.getByText('Notification Method')).toBeInTheDocument();
+    expect(
+      screen.getByText('Email subject name (optional)'),
+    ).toBeInTheDocument();
+    expect(screen.getByText('Email recipients')).toBeInTheDocument();
+  });
+
+  it('should call onRemove when the delete button is clicked', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={1}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const deleteButton = screen.getByRole('button');
+    fireEvent.click(deleteButton);
+
+    expect(mockOnRemove).toHaveBeenCalledWith(1);
+  });
+  // Should update recipient value when input changes.
+
+  it('should update recipient value when input changes', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const recipientsInput = screen.getByTestId('recipients');
+    fireEvent.change(recipientsInput, {
+      target: { value: '[email protected]' },
+    });
+
+    expect(mockOnUpdate).toHaveBeenCalledWith(0, {
+      ...mockSetting,
+      recipients: '[email protected]',
+    });
+  });
+
+  it('should call onRecipientsChange when the recipients value is changed', () 
=> {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const recipientsInput = screen.getByTestId('recipients');
+    fireEvent.change(recipientsInput, {
+      target: { value: '[email protected]' },
+    });
+
+    expect(mockOnUpdate).toHaveBeenCalledWith(0, {
+      ...mockSetting,
+      recipients: '[email protected]',
+    });
+  });
+  // correctly maps recipients when method is SlackV2
+  it('should correctly map recipients when method is SlackV2', () => {
+    const method = 'SlackV2';
+    const recipientValue = 'user1,user2';
+    const slackOptions: { label: string; value: string }[] = [
+      { label: 'User One', value: 'user1' },
+      { label: 'User Two', value: 'user2' },
+    ];
+
+    const result = mapSlackValues({ method, recipientValue, slackOptions });
+
+    expect(result).toEqual([
+      { label: 'User One', value: 'user1' },
+      { label: 'User Two', value: 'user2' },
+    ]);
+  });
+  // handles empty recipientValue string

Review Comment:
   ```suggestion
   ```



##########
superset-frontend/src/features/alerts/components/NotificationMethod.tsx:
##########
@@ -73,6 +92,68 @@ const TRANSLATIONS = {
   ),
 };
 
+export const mapSlackValues = ({
+  method,
+  recipientValue,
+  slackOptions,
+}: {
+  method: string;
+  recipientValue: string;
+  slackOptions: { label: string; value: string }[];
+}) => {
+  const prop = method === NotificationMethodOption.SlackV2 ? 'value' : 'label';
+  return recipientValue
+    .split(',')
+    .map(recipient =>
+      slackOptions.find(
+        option =>
+          option[prop].trim().toLowerCase() === recipient.trim().toLowerCase(),
+      ),
+    )
+    .filter(val => !!val) as { label: string; value: string }[];
+};
+
+export const mapChannelsToOptions = (result: SlackChannel[]) => {
+  const publicChannels: SlackChannel[] = [];
+  const privateChannels: SlackChannel[] = [];
+
+  result.forEach(channel => {
+    if (channel.is_private) {
+      privateChannels.push(channel);
+    } else {
+      publicChannels.push(channel);
+    }
+  });
+
+  return [
+    {
+      label: 'Public Channels',
+      options: publicChannels.map((channel: SlackChannel) => ({
+        label: `${channel.name} ${
+          channel.is_member ? '' : '(Bot not in channel)'
+        }`,
+        value: channel.id,
+        key: channel.id,
+      })),
+      key: 'public',
+    },
+    {
+      label: 'Private Channels (Bot in channel)',

Review Comment:
   Does it need to be localized?



##########
superset-frontend/src/features/alerts/components/NotificationMethod.test.tsx:
##########
@@ -0,0 +1,182 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { render, screen, fireEvent } from 'spec/helpers/testing-library';
+import { NotificationMethod, mapSlackValues } from './NotificationMethod';
+import { NotificationMethodOption, NotificationSetting } from '../types';
+
+const mockOnUpdate = jest.fn();
+const mockOnRemove = jest.fn();
+const mockOnInputChange = jest.fn();
+const mockSetErrorSubject = jest.fn();
+
+const mockSetting: NotificationSetting = {
+  method: NotificationMethodOption.Email,
+  recipients: '[email protected]',
+  options: [
+    NotificationMethodOption.Email,
+    NotificationMethodOption.Slack,
+    NotificationMethodOption.SlackV2,
+  ],
+};
+
+const mockEmailSubject = 'Test Subject';
+const mockDefaultSubject = 'Default Subject';
+
+describe('NotificationMethod', () => {
+  beforeEach(() => {
+    jest.clearAllMocks();
+  });
+
+  it('should render the component', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    expect(screen.getByText('Notification Method')).toBeInTheDocument();
+    expect(
+      screen.getByText('Email subject name (optional)'),
+    ).toBeInTheDocument();
+    expect(screen.getByText('Email recipients')).toBeInTheDocument();
+  });
+
+  it('should call onRemove when the delete button is clicked', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={1}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const deleteButton = screen.getByRole('button');
+    fireEvent.click(deleteButton);
+
+    expect(mockOnRemove).toHaveBeenCalledWith(1);
+  });
+  // Should update recipient value when input changes.
+
+  it('should update recipient value when input changes', () => {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const recipientsInput = screen.getByTestId('recipients');
+    fireEvent.change(recipientsInput, {
+      target: { value: '[email protected]' },
+    });
+
+    expect(mockOnUpdate).toHaveBeenCalledWith(0, {
+      ...mockSetting,
+      recipients: '[email protected]',
+    });
+  });
+
+  it('should call onRecipientsChange when the recipients value is changed', () 
=> {
+    render(
+      <NotificationMethod
+        setting={mockSetting}
+        index={0}
+        onUpdate={mockOnUpdate}
+        onRemove={mockOnRemove}
+        onInputChange={mockOnInputChange}
+        email_subject={mockEmailSubject}
+        defaultSubject={mockDefaultSubject}
+        setErrorSubject={mockSetErrorSubject}
+      />,
+    );
+
+    const recipientsInput = screen.getByTestId('recipients');
+    fireEvent.change(recipientsInput, {
+      target: { value: '[email protected]' },
+    });
+
+    expect(mockOnUpdate).toHaveBeenCalledWith(0, {
+      ...mockSetting,
+      recipients: '[email protected]',
+    });
+  });
+  // correctly maps recipients when method is SlackV2
+  it('should correctly map recipients when method is SlackV2', () => {
+    const method = 'SlackV2';
+    const recipientValue = 'user1,user2';
+    const slackOptions: { label: string; value: string }[] = [
+      { label: 'User One', value: 'user1' },
+      { label: 'User Two', value: 'user2' },
+    ];
+
+    const result = mapSlackValues({ method, recipientValue, slackOptions });
+
+    expect(result).toEqual([
+      { label: 'User One', value: 'user1' },
+      { label: 'User Two', value: 'user2' },
+    ]);
+  });
+  // handles empty recipientValue string
+  it('should return an empty array when recipientValue is an empty string', () 
=> {
+    const method = 'SlackV2';
+    const recipientValue = '';
+    const slackOptions: { label: string; value: string }[] = [
+      { label: 'User One', value: 'user1' },
+      { label: 'User Two', value: 'user2' },
+    ];
+
+    const result = mapSlackValues({ method, recipientValue, slackOptions });
+
+    expect(result).toEqual([]);
+  });
+  // Ensure that the mapSlackValues function correctly maps recipients when 
the method is Slack with updated recipient values

Review Comment:
   ```suggestion
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to