Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ML] Migrate SelectInterval/SelectSeverity unit tests from enzyme to react-testing-lib #153321

Merged
merged 7 commits into from
Mar 23, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,58 +5,39 @@
* 2.0.
*/

import React from 'react';
import { act } from 'react-dom/test-utils';
import { MemoryRouter } from 'react-router-dom';
import { mount } from 'enzyme';

import { EuiSelect } from '@elastic/eui';

import { UrlStateProvider } from '@kbn/ml-url-state';
import React, { useState } from 'react';
import { render, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import { SelectInterval } from './select_interval';

describe('SelectInterval', () => {
test('creates correct initial selected value', () => {
const wrapper = mount(
<MemoryRouter>
<UrlStateProvider>
<SelectInterval />
</UrlStateProvider>
</MemoryRouter>
);
const select = wrapper.find(EuiSelect);
// The following mock setup is necessary so that we can simulate
// both triggering the update callback and the internal state update
// to update the dropdown to the new state.
const mockUpdateCallback = jest.fn();
const mockUseState = jest.fn().mockImplementation(useState);
jest.mock('@kbn/ml-url-state', () => ({
usePageUrlState: () => {
const [interval, setInterval] = mockUseState({ display: 'Auto', val: 'auto' });
return [interval, mockUpdateCallback.mockImplementation((d) => setInterval(d))];
},
}));

const defaultSelectedValue = select.props().value;
expect(defaultSelectedValue).toBe('auto');
});

test('currently selected value is updated correctly on click', (done) => {
const wrapper = mount(
<MemoryRouter>
<UrlStateProvider>
<SelectInterval />
</UrlStateProvider>
</MemoryRouter>
);
const select = wrapper.find(EuiSelect).first();
const defaultSelectedValue = select.props().value;
expect(defaultSelectedValue).toBe('auto');
describe('SelectInterval', () => {
it('updates the selected value correctly on click', () => {
// prepare
darnautov marked this conversation as resolved.
Show resolved Hide resolved
const { getByText, getByTestId } = render(<SelectInterval />);

const onChange = select.props().onChange;
// assert initial state
expect((getByText('Auto') as HTMLOptionElement).selected).toBeTruthy();

// update
act(() => {
if (onChange !== undefined) {
onChange({ target: { value: 'day' } } as React.ChangeEvent<HTMLSelectElement>);
}
userEvent.selectOptions(getByTestId('mlAnomalyIntervalControls'), getByText('1 hour'));
});

setImmediate(() => {
wrapper.update();
const updatedSelect = wrapper.find(EuiSelect).first();
const updatedSelectedValue = updatedSelect.props().value;
expect(updatedSelectedValue).toBe('day');
done();
});
// assert updated state
expect(mockUpdateCallback).toBeCalledWith({ display: '1 hour', val: 'hour' });
expect((getByText('1 hour') as HTMLOptionElement).selected).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export const SelectIntervalUI: FC<SelectIntervalUIProps> = ({ interval, onChange

return (
<EuiSelect
data-test-subj="mlAnomalyIntervalControls"
prepend={i18n.translate('xpack.ml.explorer.intervalLabel', {
defaultMessage: 'Interval',
})}
Expand All @@ -101,7 +102,6 @@ export const SelectIntervalUI: FC<SelectIntervalUIProps> = ({ interval, onChange
</EuiToolTip>
}
compressed
id="selectInterval"
options={OPTIONS}
value={interval.val}
onChange={handleOnChange}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,96 +4,63 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from 'react';
import { act } from 'react-dom/test-utils';
import { MemoryRouter } from 'react-router-dom';
import { mount } from 'enzyme';

import { EuiSuperSelect } from '@elastic/eui';

import { UrlStateProvider } from '@kbn/ml-url-state';

import { SelectSeverity } from './select_severity';
import React, { useState } from 'react';
import { render, act, fireEvent, waitFor } from '@testing-library/react';
import { __IntlProvider as IntlProvider } from '@kbn/i18n-react';

import { SelectSeverity, SEVERITY_OPTIONS } from './select_severity';

// The following mock setup is necessary so that we can simulate
// both triggering the update callback and the internal state update
// to update the dropdown to the new state.
const mockSeverityOptions = SEVERITY_OPTIONS;
const mockUpdateCallback = jest.fn();
const mockUseState = jest.fn().mockImplementation(useState);
jest.mock('@kbn/ml-url-state', () => ({
usePageUrlState: () => {
const [severity, setSeverity] = mockUseState(mockSeverityOptions[0]);
return [severity, mockUpdateCallback.mockImplementation((d) => setSeverity(d))];
},
}));

describe('SelectSeverity', () => {
test('creates correct severity options and initial selected value', () => {
const wrapper = mount(
<MemoryRouter>
<UrlStateProvider>
<SelectSeverity />
</UrlStateProvider>
</MemoryRouter>
);
const select = wrapper.find(EuiSuperSelect);

const options = select.props().options;
const defaultSelectedValue = select.props().valueOfSelected;

expect(defaultSelectedValue).toBe('warning');
expect(options.length).toEqual(4);

// excpect options Array to equal Array containing Object that contains the property
expect(options).toEqual(
expect.arrayContaining([
expect.objectContaining({
value: 'warning',
}),
])
);

expect(options).toEqual(
expect.arrayContaining([
expect.objectContaining({
value: 'minor',
}),
])
);

expect(options).toEqual(
expect.arrayContaining([
expect.objectContaining({
value: 'major',
}),
])
it('updates the severity option correctly on click', async () => {
darnautov marked this conversation as resolved.
Show resolved Hide resolved
// prepare
const { getByText, getAllByText, queryByText, getByTestId } = render(
<IntlProvider locale="en">
<SelectSeverity />
</IntlProvider>
);

expect(options).toEqual(
expect.arrayContaining([
expect.objectContaining({
value: 'critical',
}),
])
);
});
// assert initial state
expect(getAllByText('warning')).toHaveLength(2);
expect(queryByText('minor')).not.toBeInTheDocument();
expect(queryByText('major')).not.toBeInTheDocument();
expect(queryByText('critical')).not.toBeInTheDocument();

test('state for currently selected value is updated correctly on click', (done) => {
const wrapper = mount(
<MemoryRouter>
<UrlStateProvider>
<SelectSeverity />
</UrlStateProvider>
</MemoryRouter>
);

const select = wrapper.find(EuiSuperSelect).first();
const defaultSelectedValue = select.props().valueOfSelected;
expect(defaultSelectedValue).toBe('warning');
// open popover
act(() => {
fireEvent.click(getByTestId('mlAnomalySeverityThresholdControls'));
});

const onChange = select.props().onChange;
// assert open popover
expect(getAllByText('warning')).toHaveLength(3);
expect(getAllByText('minor')).toHaveLength(1);
expect(getAllByText('major')).toHaveLength(1);
expect(getAllByText('critical')).toHaveLength(1);

// click item in popver
act(() => {
if (onChange !== undefined) {
onChange('critical');
}
fireEvent.click(getByText('major'));
});

setImmediate(() => {
wrapper.update();
const updatedSelect = wrapper.find(EuiSuperSelect).first();
const updatedSelectedValue = updatedSelect.props().valueOfSelected;
expect(updatedSelectedValue).toBe('critical');
done();
// assert updated state
expect(mockUpdateCallback).toBeCalledWith(SEVERITY_OPTIONS[2]);
await waitFor(() => {
expect(queryByText('warning')).not.toBeInTheDocument();
expect(queryByText('minor')).not.toBeInTheDocument();
expect(getAllByText('major')).toHaveLength(2);
expect(queryByText('critical')).not.toBeInTheDocument();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ export const SelectSeverityUI: FC<
prepend={i18n.translate('xpack.ml.explorer.severityThresholdLabel', {
defaultMessage: 'Severity',
})}
id="severityThreshold"
data-test-subj={'mlAnomalySeverityThresholdControls'}
className={classNames}
hasDividers
Expand Down