Skip to content

Commit

Permalink
fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
XavierM committed Jun 21, 2023
1 parent 4bc468f commit d7862fd
Show file tree
Hide file tree
Showing 8 changed files with 37 additions and 87 deletions.
Expand Up @@ -6,20 +6,18 @@
*/

import React from 'react';
import { act, render, fireEvent, screen, waitFor } from '@testing-library/react';
import { act, render, fireEvent, screen } from '@testing-library/react';
import { useKibana } from '@kbn/triggers-actions-ui-plugin/public';
import SlackActionFields from './slack_connectors';

import { ConnectorFormTestProvider, waitForComponentToUpdate } from '../lib/test_utils';
import userEvent from '@testing-library/user-event';
import SlackActionFields from './slack_connectors';
import { useFetchChannels } from './use_fetch_channels';

jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana');
jest.mock('./use_fetch_channels');

const postMock = jest.fn();
(useKibana as jest.Mock).mockImplementation(() => ({
services: {
http: {
post: postMock,
},
docLinks: {
links: {
alerting: { slackApiAction: 'url' },
Expand All @@ -34,6 +32,11 @@ const postMock = jest.fn();
},
}));

(useFetchChannels as jest.Mock).mockImplementation(() => ({
channels: [],
isLoading: false,
}));

describe('SlackActionFields renders', () => {
const onSubmit = jest.fn();
beforeEach(() => {
Expand Down Expand Up @@ -141,15 +144,9 @@ describe('SlackActionFields renders', () => {
});

it('Allowed Channels combobox should NOT be disable when there is token', async () => {
/*
* WHY we will do that
* There is something wrong with the combobox from EUI, updating a state when the combobox is not mounted anymore :(
* which is populating our test console, so I decided to remove it since we know the reason.
*/
jest.spyOn(console, 'error').mockImplementation(jest.fn());
const actionConnector = {
secrets: {
token: '',
token: 'qwertyuiopasdfghjklzxcvbnm',
},
config: {
allowedChannels: ['foo', 'bar'],
Expand All @@ -159,33 +156,22 @@ describe('SlackActionFields renders', () => {
name: 'slack',
isDeprecated: false,
};
postMock.mockResolvedValue({
ok: true,
channels: ['foo', 'bar', 'hello', 'world'],
});

(useFetchChannels as jest.Mock).mockImplementation(() => ({
channels: [{ label: 'foo' }, { label: 'bar' }, { label: 'hello' }, { label: 'world' }],
isLoading: false,
}));

const { container } = render(
<ConnectorFormTestProvider connector={actionConnector} onSubmit={onSubmit}>
<SlackActionFields readOnly={false} isEdit={false} registerPreSubmitValidator={() => {}} />
</ConnectorFormTestProvider>
);

await act(async () => {
await userEvent.type(
screen.getByTestId('secrets.token-input'),
`qwertyuiopasdfghjklzxcvbnm`,
{
delay: 10,
}
);
});

waitFor(() => {
expect(
container.querySelector(
'[data-test-subj="config.allowedChannels-input"].euiComboBox-isDisabled'
)
).not.toBeInTheDocument();
});
expect(
container.querySelector(
'[data-test-subj="config.allowedChannels-input"].euiComboBox-isDisabled'
)
).not.toBeInTheDocument();
});
});
Expand Up @@ -67,7 +67,9 @@ const getConfigFormSchemaAfterSecrets = (
},
];

const SlackActionFieldsComponents: React.FC<ActionConnectorFieldsProps> = ({
const NO_SCHEMA: ConfigFieldSchema[] = [];

export const SlackActionFieldsComponents: React.FC<ActionConnectorFieldsProps> = ({
readOnly,
isEdit,
}) => {
Expand All @@ -79,7 +81,6 @@ const SlackActionFieldsComponents: React.FC<ActionConnectorFieldsProps> = ({
const [authToken, setAuthToken] = useState('');

const { channels, isLoading } = useFetchChannels({ authToken });

const configFormSchemaAfterSecrets = useMemo(
() => getConfigFormSchemaAfterSecrets(channels, isLoading, channels.length === 0),
[channels, isLoading]
Expand All @@ -94,7 +95,7 @@ const SlackActionFieldsComponents: React.FC<ActionConnectorFieldsProps> = ({
}, [formData.secrets]);

useEffect(() => {
if (isEmpty(authToken)) {
if (isEmpty(authToken) && channels.length > 0) {
setFieldValue('config.allowedChannels', []);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand All @@ -104,7 +105,7 @@ const SlackActionFieldsComponents: React.FC<ActionConnectorFieldsProps> = ({
<SimpleConnectorForm
isEdit={isEdit}
readOnly={readOnly}
configFormSchema={[]}
configFormSchema={NO_SCHEMA}
secretsFormSchema={getSecretsFormSchema(docLinks)}
configFormSchemaAfterSecrets={configFormSchemaAfterSecrets}
/>
Expand Down
Expand Up @@ -74,16 +74,14 @@ const SlackParamsFields: React.FunctionComponent<ActionParamsProps<PostMessagePa
const [selectedChannels, setSelectedChannels] = useState<EuiComboBoxOptionOption[]>(
(channels ?? []).map((c) => ({ label: c }))
);
const [createdChannels, setCreatedChannels] = useState<EuiComboBoxOptionOption[]>([]);

const slackChannels = useMemo(() => {
const slackChannelsTmp =
const slackChannels = useMemo(
() =>
channelsInfo
?.filter((slackChannel) => slackChannel.is_channel)
.map((slackChannel) => ({ label: slackChannel.name })) ?? [];
slackChannelsTmp.push(...createdChannels);
return slackChannelsTmp;
}, [channelsInfo, createdChannels]);
.map((slackChannel) => ({ label: slackChannel.name })) ?? [],
[channelsInfo]
);

const onChange = useCallback(
(newOptions: EuiComboBoxOptionOption[]) => {
Expand Down
Expand Up @@ -310,7 +310,7 @@ describe('execute', () => {
configurationUtilities,
logger: mockedLogger,
method: 'get',
url: 'conversations.list?types=public_channel,private_channel',
url: 'conversations.list?exclude_archived=true&types=public_channel,private_channel&limit=1000',
});

expect(response).toEqual({
Expand Down
Expand Up @@ -128,7 +128,7 @@ describe('Slack API service', () => {
logger,
configurationUtilities,
method: 'get',
url: 'conversations.list?types=public_channel,private_channel',
url: 'conversations.list?exclude_archived=true&types=public_channel,private_channel&limit=1000',
});
});

Expand Down Expand Up @@ -193,7 +193,7 @@ describe('Slack API service', () => {
).toEqual({
actionId: SLACK_API_CONNECTOR_ID,
serviceMessage:
'One of these channels "general,privat" is/are not valid with the allowed channels list "foo,bar" ',
'The channel "general,privat" is not included in the allowed channels list "foo,bar"',
message: 'error posting slack message',
status: 'error',
});
Expand Down
Expand Up @@ -208,7 +208,7 @@ export const createExternalService = (
) {
return buildSlackExecutorErrorResponse({
slackApiError: {
message: `The channel "${channels.join()}" is not included in the allowed channels list "${allowedChannels.join()}" `,
message: `The channel "${channels.join()}" is not included in the allowed channels list "${allowedChannels.join()}"`,
},
logger,
});
Expand Down

This file was deleted.

Expand Up @@ -201,9 +201,9 @@ const SimpleConnectorFormComponent: React.FC<SimpleConnectorFormProps> = ({
{index !== secretsFormSchema.length ? <EuiSpacer size="m" /> : null}
</React.Fragment>
))}
{configFormSchemaAfterSecrets.map(({ id, ...restConfigSchema }, index) => (
{configFormSchemaAfterSecrets.map(({ id, ...restConfigSchemaAfterSecrets }, index) => (
<React.Fragment key={`config.${id}`}>
<FormRow id={`config.${id}`} {...restConfigSchema} readOnly={readOnly} />
<FormRow id={`config.${id}`} {...restConfigSchemaAfterSecrets} readOnly={readOnly} />
{index !== configFormSchemaAfterSecrets.length ? <EuiSpacer size="m" /> : null}
</React.Fragment>
))}
Expand Down

0 comments on commit d7862fd

Please sign in to comment.