[Lens] remove react warnings (#59574)

This commit is contained in:
Marta Bondyra 2020-03-10 22:10:35 +01:00 committed by GitHub
parent 8478734247
commit 44eb7c0130
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 748 additions and 782 deletions

View file

@ -38,11 +38,6 @@ jest
const { TopNavMenu } = npStart.plugins.navigation.ui;
const waitForPromises = async () =>
act(async () => {
await new Promise(resolve => setTimeout(resolve));
});
function createMockFrame(): jest.Mocked<EditorFrameInstance> {
return {
mount: jest.fn((el, props) => {}),
@ -86,6 +81,7 @@ function createMockFilterManager() {
describe('Lens App', () => {
let frame: jest.Mocked<EditorFrameInstance>;
let core: ReturnType<typeof coreMock['createStart']>;
let instance: ReactWrapper;
function makeDefaultArgs(): jest.Mocked<{
editorFrame: EditorFrameInstance;
@ -205,7 +201,7 @@ describe('Lens App', () => {
it('sets breadcrumbs when the document title changes', async () => {
const defaultArgs = makeDefaultArgs();
const instance = mount(<App {...defaultArgs} />);
instance = mount(<App {...defaultArgs} />);
expect(core.chrome.setBreadcrumbs).toHaveBeenCalledWith([
{ text: 'Visualize', href: '/testbasepath/app/kibana#/visualize' },
@ -221,10 +217,9 @@ describe('Lens App', () => {
datasourceMetaData: { filterableIndexPatterns: [{ id: '1', title: 'saved' }] },
},
});
instance.setProps({ docId: '1234' });
await waitForPromises();
await act(async () => {
instance.setProps({ docId: '1234' });
});
expect(defaultArgs.core.chrome.setBreadcrumbs).toHaveBeenCalledWith([
{ text: 'Visualize', href: '/testbasepath/app/kibana#/visualize' },
@ -254,10 +249,11 @@ describe('Lens App', () => {
},
});
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
instance.setProps({ docId: '1234' });
await waitForPromises();
await act(async () => {
instance.setProps({ docId: '1234' });
});
expect(args.docStorage.load).toHaveBeenCalledWith('1234');
expect(args.data.indexPatterns.get).toHaveBeenCalledWith('1');
@ -292,17 +288,20 @@ describe('Lens App', () => {
args.editorFrame = frame;
(args.docStorage.load as jest.Mock).mockResolvedValue({ id: '1234' });
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
await act(async () => {
instance.setProps({ docId: '1234' });
});
instance.setProps({ docId: '1234' });
await waitForPromises();
instance.setProps({ docId: '1234' });
await waitForPromises();
await act(async () => {
instance.setProps({ docId: '1234' });
});
expect(args.docStorage.load).toHaveBeenCalledTimes(1);
instance.setProps({ docId: '9876' });
await waitForPromises();
await act(async () => {
instance.setProps({ docId: '9876' });
});
expect(args.docStorage.load).toHaveBeenCalledTimes(2);
});
@ -312,10 +311,11 @@ describe('Lens App', () => {
args.editorFrame = frame;
(args.docStorage.load as jest.Mock).mockRejectedValue('failed to load');
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
instance.setProps({ docId: '1234' });
await waitForPromises();
await act(async () => {
instance.setProps({ docId: '1234' });
});
expect(args.docStorage.load).toHaveBeenCalledWith('1234');
expect(args.core.notifications.toasts.addDanger).toHaveBeenCalled();
@ -353,22 +353,20 @@ describe('Lens App', () => {
} as jest.ResolvedValue<Document>);
});
function getButton(instance: ReactWrapper): TopNavMenuData {
return (instance
function getButton(inst: ReactWrapper): TopNavMenuData {
return (inst
.find('[data-test-subj="lnsApp_topNav"]')
.prop('config') as TopNavMenuData[]).find(
button => button.testId === 'lnsApp_saveButton'
)!;
}
function testSave(instance: ReactWrapper, saveProps: SaveProps) {
act(() => {
getButton(instance).run(instance.getDOMNode());
});
async function testSave(inst: ReactWrapper, saveProps: SaveProps) {
await getButton(inst).run(inst.getDOMNode());
instance.update();
inst.update();
const handler = instance.findWhere(el => el.prop('onSave')).prop('onSave') as (
const handler = inst.findWhere(el => el.prop('onSave')).prop('onSave') as (
p: unknown
) => void;
handler(saveProps);
@ -406,9 +404,9 @@ describe('Lens App', () => {
expression: 'kibana 2',
}));
const instance = mount(<App {...args} />);
await waitForPromises();
await act(async () => {
instance = mount(<App {...args} />);
});
if (initialDocId) {
expect(args.docStorage.load).toHaveBeenCalledTimes(1);
@ -427,9 +425,10 @@ describe('Lens App', () => {
instance.update();
expect(getButton(instance).disableButton).toEqual(false);
testSave(instance, saveProps);
await waitForPromises();
await act(async () => {
testSave(instance, saveProps);
});
return { args, instance };
}
@ -445,7 +444,7 @@ describe('Lens App', () => {
};
args.editorFrame = frame;
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
expect(getButton(instance).disableButton).toEqual(true);
@ -469,7 +468,7 @@ describe('Lens App', () => {
} as jest.ResolvedValue<Document>);
args.editorFrame = frame;
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
expect(getButton(instance).disableButton).toEqual(true);
const onChange = frame.mount.mock.calls[0][1].onChange;
@ -488,7 +487,7 @@ describe('Lens App', () => {
const args = defaultArgs;
args.editorFrame = frame;
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
expect(getButton(instance).disableButton).toEqual(true);
@ -505,7 +504,7 @@ describe('Lens App', () => {
});
it('saves new docs', async () => {
const { args, instance } = await save({
const { args, instance: inst } = await save({
initialDocId: undefined,
newCopyOnSave: false,
newTitle: 'hello there',
@ -519,13 +518,13 @@ describe('Lens App', () => {
expect(args.redirectTo).toHaveBeenCalledWith('aaa');
instance.setProps({ docId: 'aaa' });
inst.setProps({ docId: 'aaa' });
expect(args.docStorage.load).not.toHaveBeenCalled();
});
it('saves the latest doc as a copy', async () => {
const { args, instance } = await save({
const { args, instance: inst } = await save({
initialDocId: '1234',
newCopyOnSave: true,
newTitle: 'hello there',
@ -539,13 +538,13 @@ describe('Lens App', () => {
expect(args.redirectTo).toHaveBeenCalledWith('aaa');
instance.setProps({ docId: 'aaa' });
inst.setProps({ docId: 'aaa' });
expect(args.docStorage.load).toHaveBeenCalledTimes(1);
});
it('saves existing docs', async () => {
const { args, instance } = await save({
const { args, instance: inst } = await save({
initialDocId: '1234',
newCopyOnSave: false,
newTitle: 'hello there',
@ -559,7 +558,7 @@ describe('Lens App', () => {
expect(args.redirectTo).not.toHaveBeenCalled();
instance.setProps({ docId: '1234' });
inst.setProps({ docId: '1234' });
expect(args.docStorage.load).toHaveBeenCalledTimes(1);
});
@ -569,7 +568,7 @@ describe('Lens App', () => {
args.editorFrame = frame;
(args.docStorage.save as jest.Mock).mockRejectedValue({ message: 'failed' });
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
const onChange = frame.mount.mock.calls[0][1].onChange;
act(() =>
@ -581,13 +580,12 @@ describe('Lens App', () => {
instance.update();
testSave(instance, { newCopyOnSave: false, newTitle: 'hello there' });
await waitForPromises();
await act(async () => {
testSave(instance, { newCopyOnSave: false, newTitle: 'hello there' });
});
expect(args.core.notifications.toasts.addDanger).toHaveBeenCalled();
expect(args.redirectTo).not.toHaveBeenCalled();
await waitForPromises();
expect(getButton(instance).disableButton).toEqual(false);
});
@ -616,8 +614,10 @@ describe('Lens App', () => {
const unpinned = esFilters.buildExistsFilter(field, indexPattern);
const pinned = esFilters.buildExistsFilter(pinnedField, indexPattern);
FilterManager.setFiltersStore([pinned], esFilters.FilterStateStore.GLOBAL_STATE);
await waitForPromises();
await act(async () => {
FilterManager.setFiltersStore([pinned], esFilters.FilterStateStore.GLOBAL_STATE);
});
const { args } = await save({
initialDocId: '1234',
@ -695,7 +695,7 @@ describe('Lens App', () => {
const args = defaultArgs;
args.editorFrame = frame;
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
expect(TopNavMenu).toHaveBeenCalledWith(
expect.objectContaining({
@ -705,14 +705,14 @@ describe('Lens App', () => {
);
const onChange = frame.mount.mock.calls[0][1].onChange;
act(() =>
await act(async () => {
onChange({
filterableIndexPatterns: [{ id: '1', title: 'newIndex' }],
doc: ({ id: undefined, expression: 'valid expression' } as unknown) as Document,
})
);
});
});
await waitForPromises();
instance.update();
expect(TopNavMenu).toHaveBeenCalledWith(
@ -723,14 +723,13 @@ describe('Lens App', () => {
);
// Do it again to verify that the dirty checking is done right
act(() =>
await act(async () => {
onChange({
filterableIndexPatterns: [{ id: '2', title: 'second index' }],
doc: ({ id: undefined, expression: 'valid expression' } as unknown) as Document,
})
);
await waitForPromises();
});
});
instance.update();
@ -745,7 +744,7 @@ describe('Lens App', () => {
const args = defaultArgs;
args.editorFrame = frame;
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
act(() =>
instance.find(TopNavMenu).prop('onQuerySubmit')!({
@ -777,7 +776,7 @@ describe('Lens App', () => {
const args = defaultArgs;
args.editorFrame = frame;
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
const indexPattern = ({ id: 'index1' } as unknown) as IIndexPattern;
const field = ({ name: 'myfield' } as unknown) as IFieldType;
@ -819,7 +818,7 @@ describe('Lens App', () => {
const args = makeDefaultArgs();
args.editorFrame = frame;
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
expect(TopNavMenu).toHaveBeenCalledWith(
expect.objectContaining({
@ -862,7 +861,7 @@ describe('Lens App', () => {
const args = makeDefaultArgs();
args.editorFrame = frame;
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
act(() => {
instance.find(TopNavMenu).prop('onSaved')!({
@ -905,7 +904,7 @@ describe('Lens App', () => {
const args = makeDefaultArgs();
args.editorFrame = frame;
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
act(() =>
instance.find(TopNavMenu).prop('onQuerySubmit')!({
@ -941,7 +940,7 @@ describe('Lens App', () => {
const args = makeDefaultArgs();
args.editorFrame = frame;
const instance = mount(<App {...args} />);
instance = mount(<App {...args} />);
const onError = frame.mount.mock.calls[0][1].onError;
onError({ message: 'error' });

View file

@ -7,6 +7,7 @@
import React from 'react';
import { mountWithIntl as mount } from 'test_utils/enzyme_helpers';
import { debouncedComponent } from './debounced_component';
import { act } from 'react-dom/test-utils';
describe('debouncedComponent', () => {
test('immediately renders', () => {
@ -23,7 +24,9 @@ describe('debouncedComponent', () => {
const component = mount(<TestComponent title="there" />);
component.setProps({ title: 'yall' });
expect(component.text()).toEqual('there');
await new Promise(r => setTimeout(r, 1));
await act(async () => {
await new Promise(r => setTimeout(r, 1));
});
expect(component.text()).toEqual('yall');
});
});

View file

@ -23,11 +23,6 @@ import { Ast } from '@kbn/interpreter/common';
import { coreMock } from 'src/core/public/mocks';
import { esFilters, IFieldType, IIndexPattern } from '../../../../../../../src/plugins/data/public';
const waitForPromises = async () =>
act(async () => {
await new Promise(resolve => setTimeout(resolve));
});
describe('workspace_panel', () => {
let mockVisualization: jest.Mocked<Visualization>;
let mockVisualization2: jest.Mocked<Visualization>;
@ -299,41 +294,43 @@ describe('workspace_panel', () => {
expressionRendererMock = jest.fn(_arg => <span />);
instance = mount(
<InnerWorkspacePanel
activeDatasourceId={'mock'}
datasourceStates={{
mock: {
state: {},
isLoading: false,
},
}}
datasourceMap={{
mock: mockDatasource,
}}
framePublicAPI={framePublicAPI}
activeVisualizationId="vis"
visualizationMap={{
vis: { ...mockVisualization, toExpression: () => 'vis' },
}}
visualizationState={{}}
dispatch={() => {}}
ExpressionRenderer={expressionRendererMock}
core={coreMock.createSetup()}
/>
);
// "wait" for the expression to execute
await waitForPromises();
await act(async () => {
instance = mount(
<InnerWorkspacePanel
activeDatasourceId={'mock'}
datasourceStates={{
mock: {
state: {},
isLoading: false,
},
}}
datasourceMap={{
mock: mockDatasource,
}}
framePublicAPI={framePublicAPI}
activeVisualizationId="vis"
visualizationMap={{
vis: { ...mockVisualization, toExpression: () => 'vis' },
}}
visualizationState={{}}
dispatch={() => {}}
ExpressionRenderer={expressionRendererMock}
core={coreMock.createSetup()}
/>
);
});
instance.update();
expect(expressionRendererMock).toHaveBeenCalledTimes(1);
instance.setProps({
framePublicAPI: { ...framePublicAPI, dateRange: { fromDate: 'now-90d', toDate: 'now-30d' } },
await act(async () => {
instance.setProps({
framePublicAPI: {
...framePublicAPI,
dateRange: { fromDate: 'now-90d', toDate: 'now-30d' },
},
});
});
await waitForPromises();
instance.update();
expect(expressionRendererMock).toHaveBeenCalledTimes(2);
@ -351,33 +348,32 @@ describe('workspace_panel', () => {
.mockReturnValueOnce('datasource second');
expressionRendererMock = jest.fn(_arg => <span />);
await act(async () => {
instance = mount(
<InnerWorkspacePanel
activeDatasourceId={'mock'}
datasourceStates={{
mock: {
state: {},
isLoading: false,
},
}}
datasourceMap={{
mock: mockDatasource,
}}
framePublicAPI={framePublicAPI}
activeVisualizationId="vis"
visualizationMap={{
vis: { ...mockVisualization, toExpression: () => 'vis' },
}}
visualizationState={{}}
dispatch={() => {}}
ExpressionRenderer={expressionRendererMock}
core={coreMock.createSetup()}
/>
);
});
instance = mount(
<InnerWorkspacePanel
activeDatasourceId={'mock'}
datasourceStates={{
mock: {
state: {},
isLoading: false,
},
}}
datasourceMap={{
mock: mockDatasource,
}}
framePublicAPI={framePublicAPI}
activeVisualizationId="vis"
visualizationMap={{
vis: { ...mockVisualization, toExpression: () => 'vis' },
}}
visualizationState={{}}
dispatch={() => {}}
ExpressionRenderer={expressionRendererMock}
core={coreMock.createSetup()}
/>
);
// "wait" for the expression to execute
await waitForPromises();
instance.update();
expect(expressionRendererMock).toHaveBeenCalledTimes(1);
@ -385,14 +381,15 @@ describe('workspace_panel', () => {
const indexPattern = ({ id: 'index1' } as unknown) as IIndexPattern;
const field = ({ name: 'myfield' } as unknown) as IFieldType;
instance.setProps({
framePublicAPI: {
...framePublicAPI,
filters: [esFilters.buildExistsFilter(field, indexPattern)],
},
await act(async () => {
instance.setProps({
framePublicAPI: {
...framePublicAPI,
filters: [esFilters.buildExistsFilter(field, indexPattern)],
},
});
});
await waitForPromises();
instance.update();
expect(expressionRendererMock).toHaveBeenCalledTimes(2);
@ -442,32 +439,31 @@ describe('workspace_panel', () => {
first: mockDatasource.publicAPIMock,
};
instance = mount(
<InnerWorkspacePanel
activeDatasourceId={'mock'}
datasourceStates={{
mock: {
state: {},
isLoading: false,
},
}}
datasourceMap={{
mock: mockDatasource,
}}
framePublicAPI={framePublicAPI}
activeVisualizationId="vis"
visualizationMap={{
vis: { ...mockVisualization, toExpression: () => 'vis' },
}}
visualizationState={{}}
dispatch={() => {}}
ExpressionRenderer={expressionRendererMock}
core={coreMock.createSetup()}
/>
);
// "wait" for the expression to execute
await waitForPromises();
await act(async () => {
instance = mount(
<InnerWorkspacePanel
activeDatasourceId={'mock'}
datasourceStates={{
mock: {
state: {},
isLoading: false,
},
}}
datasourceMap={{
mock: mockDatasource,
}}
framePublicAPI={framePublicAPI}
activeVisualizationId="vis"
visualizationMap={{
vis: { ...mockVisualization, toExpression: () => 'vis' },
}}
visualizationState={{}}
dispatch={() => {}}
ExpressionRenderer={expressionRendererMock}
core={coreMock.createSetup()}
/>
);
});
instance.update();
@ -486,32 +482,31 @@ describe('workspace_panel', () => {
first: mockDatasource.publicAPIMock,
};
instance = mount(
<InnerWorkspacePanel
activeDatasourceId={'mock'}
datasourceStates={{
mock: {
state: {},
isLoading: false,
},
}}
datasourceMap={{
mock: mockDatasource,
}}
framePublicAPI={framePublicAPI}
activeVisualizationId="vis"
visualizationMap={{
vis: { ...mockVisualization, toExpression: () => 'vis' },
}}
visualizationState={{}}
dispatch={() => {}}
ExpressionRenderer={expressionRendererMock}
core={coreMock.createSetup()}
/>
);
// "wait" for the expression to execute
await waitForPromises();
await act(async () => {
instance = mount(
<InnerWorkspacePanel
activeDatasourceId={'mock'}
datasourceStates={{
mock: {
state: {},
isLoading: false,
},
}}
datasourceMap={{
mock: mockDatasource,
}}
framePublicAPI={framePublicAPI}
activeVisualizationId="vis"
visualizationMap={{
vis: { ...mockVisualization, toExpression: () => 'vis' },
}}
visualizationState={{}}
dispatch={() => {}}
ExpressionRenderer={expressionRendererMock}
core={coreMock.createSetup()}
/>
);
});
instance.update();

View file

@ -269,13 +269,6 @@ describe('IndexPattern Data Panel', () => {
});
describe('loading existence data', () => {
function waitForPromises() {
return Promise.resolve()
.catch(() => {})
.then(() => {})
.then(() => {});
}
function testProps() {
const setState = jest.fn();
core.http.get.mockImplementation(async ({ path }) => {
@ -318,14 +311,12 @@ describe('IndexPattern Data Panel', () => {
const props = testProps();
const inst = mountWithIntl(<IndexPatternDataPanel {...props} />);
act(() => {
await act(async () => {
inst.update();
});
await waitForPromises();
if (stateChanges || propChanges) {
act(() => {
await act(async () => {
((inst.setProps as unknown) as (props: unknown) => {})({
...props,
...((propChanges as object) || {}),
@ -336,7 +327,6 @@ describe('IndexPattern Data Panel', () => {
});
inst.update();
});
await waitForPromises();
}
return props.setState;
@ -473,13 +463,11 @@ describe('IndexPattern Data Panel', () => {
});
it('shows a loading indicator when loading', async () => {
const load = async () => {};
const inst = mountWithIntl(<IndexPatternDataPanel {...testProps()} />);
expect(inst.find(EuiProgress).length).toEqual(1);
await waitForPromises();
await act(load);
inst.update();
expect(inst.find(EuiProgress).length).toEqual(0);
});
@ -520,7 +508,7 @@ describe('IndexPattern Data Panel', () => {
inst.update();
});
act(() => {
await act(async () => {
((inst.setProps as unknown) as (props: unknown) => {})({
...props,
dateRange: { fromDate: '2019-01-01', toDate: '2020-01-03' },
@ -528,8 +516,6 @@ describe('IndexPattern Data Panel', () => {
inst.update();
});
await waitForPromises();
expect(core.http.get).toHaveBeenCalledTimes(2);
expect(overlapCount).toEqual(0);
});

View file

@ -16,11 +16,6 @@ import { IndexPattern } from './types';
jest.mock('ui/new_platform');
const waitForPromises = async () =>
act(async () => {
await new Promise(resolve => setTimeout(resolve));
});
describe('IndexPattern Field Item', () => {
let defaultProps: FieldItemProps;
let indexPattern: IndexPattern;
@ -99,7 +94,10 @@ describe('IndexPattern Field Item', () => {
return Promise.resolve({});
});
const wrapper = mountWithIntl(<FieldItem {...defaultProps} />);
wrapper.find('[data-test-subj="lnsFieldListPanelField-bytes"]').simulate('click');
await act(async () => {
wrapper.find('[data-test-subj="lnsFieldListPanelField-bytes"]').simulate('click');
});
expect(core.http.post).toHaveBeenCalledWith(
'/api/lens/index_stats/my-fake-index-pattern/field',
@ -153,19 +151,20 @@ describe('IndexPattern Field Item', () => {
expect(wrapper.find(EuiLoadingSpinner)).toHaveLength(1);
resolveFunction!({
totalDocuments: 4633,
sampledDocuments: 4633,
sampledValues: 4633,
histogram: {
buckets: [{ count: 705, key: 0 }],
},
topValues: {
buckets: [{ count: 147, key: 0 }],
},
await act(async () => {
resolveFunction!({
totalDocuments: 4633,
sampledDocuments: 4633,
sampledValues: 4633,
histogram: {
buckets: [{ count: 705, key: 0 }],
},
topValues: {
buckets: [{ count: 147, key: 0 }],
},
});
});
await waitForPromises();
wrapper.update();
expect(wrapper.find(EuiLoadingSpinner)).toHaveLength(0);

View file

@ -8,27 +8,25 @@ import React from 'react';
import { EuiProgress } from '@elastic/eui';
import { Loader } from './loader';
import { mount } from 'enzyme';
import { act } from 'react-dom/test-utils';
describe('loader', () => {
it('shows a loading indicator when loading', async () => {
const load = jest.fn(() => Promise.resolve());
const inst = mount(<Loader loadDeps={[]} load={load} />);
expect(inst.find(EuiProgress).length).toEqual(1);
await load();
await act(async () => load());
inst.update();
expect(inst.find(EuiProgress).length).toEqual(0);
});
it('hides loading indicator when failed', async () => {
const load = jest.fn(() => Promise.reject());
const inst = mount(<Loader loadDeps={[]} load={load} />);
expect(inst.find(EuiProgress).length).toEqual(1);
await Promise.resolve();
await act(async () => Promise.resolve());
inst.update();
expect(inst.find(EuiProgress).length).toEqual(0);
@ -45,7 +43,11 @@ describe('loader', () => {
return Promise.resolve().then(() => --count);
});
const inst = mount(<Loader loadDeps={['bar']} load={load} />);
inst.setProps({ loadDeps: ['foo'] });
await act(async () => {
inst.setProps({ loadDeps: ['foo'] });
});
inst.update();
await Promise.resolve();