Skip to content

Commit

Permalink
Merge pull request #5 from dej611/lens/thresholds-tests
Browse files Browse the repository at this point in the history
Threshold tests
  • Loading branch information
mbondyra committed Sep 2, 2021
2 parents 5c5ecb5 + ead4e50 commit 40069fe
Show file tree
Hide file tree
Showing 20 changed files with 1,554 additions and 270 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,13 @@ import { LayerPanel } from './layer_panel';
import { coreMock } from 'src/core/public/mocks';
import { generateId } from '../../../id_generator';
import { mountWithProvider } from '../../../mocks';
import { layerTypes } from '../../../../common';
import { ReactWrapper } from 'enzyme';

jest.mock('../../../id_generator');

const waitMs = (time: number) => new Promise((r) => setTimeout(r, time));

let container: HTMLDivElement | undefined;

beforeEach(() => {
Expand Down Expand Up @@ -137,7 +141,7 @@ describe('ConfigPanel', () => {

const updater = () => 'updated';
updateDatasource('mockindexpattern', updater);
await new Promise((r) => setTimeout(r, 0));
await waitMs(0);
expect(lensStore.dispatch).toHaveBeenCalledTimes(1);
expect(
(lensStore.dispatch as jest.Mock).mock.calls[0][0].payload.updater(
Expand All @@ -147,7 +151,7 @@ describe('ConfigPanel', () => {

updateAll('mockindexpattern', updater, props.visualizationState);
// wait for one tick so async updater has a chance to trigger
await new Promise((r) => setTimeout(r, 0));
await waitMs(0);
expect(lensStore.dispatch).toHaveBeenCalledTimes(2);
expect(
(lensStore.dispatch as jest.Mock).mock.calls[0][0].payload.updater(
Expand Down Expand Up @@ -293,4 +297,134 @@ describe('ConfigPanel', () => {
expect(focusedEl?.children[0].getAttribute('data-test-subj')).toEqual('lns-layerPanel-1');
});
});

describe('initial default value', () => {
function prepareAndMountComponent(props: ReturnType<typeof getDefaultProps>) {
(generateId as jest.Mock).mockReturnValue(`newId`);
return mountWithProvider(
<LayerPanels {...props} />,

{
preloadedState: {
datasourceStates: {
mockindexpattern: {
isLoading: false,
state: 'state',
},
},
activeDatasourceId: 'mockindexpattern',
},
},
{
attachTo: container,
}
);
}
function clickToAddLayer(instance: ReactWrapper) {
act(() => {
instance.find('[data-test-subj="lnsLayerAddButton"]').first().simulate('click');
});
instance.update();
act(() => {
instance
.find(`[data-test-subj="lnsLayerAddButton-${layerTypes.THRESHOLD}"]`)
.first()
.simulate('click');
});
instance.update();

return waitMs(0);
}

function clickToAddDimension(instance: ReactWrapper) {
act(() => {
instance.find('[data-test-subj="lns-empty-dimension"]').last().simulate('click');
});
return waitMs(0);
}

it('should not add an initial dimension when not specified', async () => {
const props = getDefaultProps();
props.activeVisualization.getSupportedLayers = jest.fn(() => [
{ type: layerTypes.DATA, label: 'Data Layer' },
{
type: layerTypes.THRESHOLD,
label: 'Threshold layer',
},
]);
mockDatasource.initializeDimension = jest.fn();

const { instance, lensStore } = await prepareAndMountComponent(props);
await clickToAddLayer(instance);

expect(lensStore.dispatch).toHaveBeenCalledTimes(1);
});

it('should not add an initial dimension when datasource does not support it', async () => {
const props = getDefaultProps();
props.activeVisualization.getSupportedLayers = jest.fn(() => [
{ type: layerTypes.DATA, label: 'Data Layer' },
{
type: layerTypes.THRESHOLD,
label: 'Threshold layer',
},
]);

const { instance, lensStore } = await prepareAndMountComponent(props);
await clickToAddLayer(instance);

expect(lensStore.dispatch).toHaveBeenCalledTimes(1);
});

it('should use group initial dimension value when adding a new layer if available', async () => {
const props = getDefaultProps();
props.activeVisualization.getSupportedLayers = jest.fn(() => [
{ type: layerTypes.DATA, label: 'Data Layer' },
{
type: layerTypes.THRESHOLD,
label: 'Threshold layer',
initialDimensions: [
{
groupId: 'testGroup',
columnId: 'myColumn',
dataType: 'number',
label: 'Initial value',
staticValue: 100,
},
],
},
]);
mockDatasource.initializeDimension = jest.fn();

const { instance, lensStore } = await prepareAndMountComponent(props);
await clickToAddLayer(instance);

expect(lensStore.dispatch).toHaveBeenCalledTimes(2);
});

it('should add an initial dimension value when clicking on the empty dimension button', async () => {
const props = getDefaultProps();
props.activeVisualization.getSupportedLayers = jest.fn(() => [
{
type: layerTypes.DATA,
label: 'Data Layer',
initialDimensions: [
{
groupId: 'a',
columnId: 'myColumn',
dataType: 'number',
label: 'Initial value',
staticValue: 100,
},
],
},
]);
mockDatasource.initializeDimension = jest.fn();

const { instance, lensStore } = await prepareAndMountComponent(props);

await clickToAddDimension(instance);
expect(lensStore.dispatch).toHaveBeenCalledTimes(1);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ export function LayerPanels(
) === 'clear'
}
onEmptyDimensionAdd={(columnId, { groupId }) => {
addMaybeDefaultThreshold({
addInitialValueIfAvailable({
...props,
visualization,
activeDatasourceId: activeDatasourceId!,
Expand Down Expand Up @@ -255,7 +255,7 @@ export function LayerPanels(
}),
})
);
addMaybeDefaultThreshold({
addInitialValueIfAvailable({
...props,
activeDatasourceId: activeDatasourceId!,
visualization,
Expand All @@ -270,7 +270,7 @@ export function LayerPanels(
);
}

function addMaybeDefaultThreshold({
function addInitialValueIfAvailable({
activeVisualization,
visualization,
framePublicAPI,
Expand Down Expand Up @@ -298,6 +298,7 @@ function addMaybeDefaultThreshold({
const layerInfo = activeVisualization
.getSupportedLayers(visualization.state, framePublicAPI)
.find(({ type }) => type === layerType);

if (layerInfo?.initialDimensions && datasourceMap[activeDatasourceId]?.initializeDimension) {
const info = groupId
? layerInfo.initialDimensions.find(({ groupId: id }) => id === groupId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -921,4 +921,33 @@ describe('LayerPanel', () => {
expect(updateVisualization).toHaveBeenCalledTimes(1);
});
});

describe('add a new dimension', () => {
it('should call onEmptyDimensionAdd callback on new dimension creation', async () => {
mockVisualization.getConfiguration.mockReturnValue({
groups: [
{
groupLabel: 'A',
groupId: 'a',
accessors: [],
filterOperations: () => true,
supportsMoreColumns: true,
dataTestSubj: 'lnsGroup',
},
],
});
const props = getDefaultProps();
const { instance } = await mountWithProvider(<LayerPanel {...props} />);

act(() => {
instance.find('[data-test-subj="lns-empty-dimension"]').first().simulate('click');
});
instance.update();

expect(props.onEmptyDimensionAdd).toHaveBeenCalledWith(
'newid',
expect.objectContaining({ groupId: 'a' })
);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from 'react';
import {
createMockFramePublicAPI,
createMockVisualization,
mountWithProvider,
} from '../../../mocks';
import { Visualization } from '../../../types';
import { LayerSettings } from './layer_settings';

describe('LayerSettings', () => {
let mockVisualization: jest.Mocked<Visualization>;
const frame = createMockFramePublicAPI();

function getDefaultProps() {
return {
activeVisualization: mockVisualization,
layerConfigProps: {
layerId: 'myLayer',
state: {},
frame,
dateRange: { fromDate: 'now-7d', toDate: 'now' },
activeData: frame.activeData,
setState: jest.fn(),
},
};
}

beforeEach(() => {
mockVisualization = {
...createMockVisualization(),
id: 'testVis',
visualizationTypes: [
{
icon: 'empty',
id: 'testVis',
label: 'TEST1',
groupLabel: 'testVisGroup',
},
],
};
});

it('should render nothing with no custom renderer nor description', async () => {
// @ts-expect-error
mockVisualization.getDescription.mockReturnValue(undefined);
const { instance } = await mountWithProvider(<LayerSettings {...getDefaultProps()} />);
expect(instance.html()).toBe(null);
});

it('should render a static header if visualization has only a description value', async () => {
mockVisualization.getDescription.mockReturnValue({
icon: 'myIcon',
label: 'myVisualizationType',
});
const { instance } = await mountWithProvider(<LayerSettings {...getDefaultProps()} />);
expect(instance.find('StaticHeader').first().prop('label')).toBe('myVisualizationType');
});

it('should call the custom renderer if available', async () => {
mockVisualization.renderLayerHeader = jest.fn();
await mountWithProvider(<LayerSettings {...getDefaultProps()} />);
expect(mockVisualization.renderLayerHeader).toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,11 @@ export function DimensionEditor(props: DimensionEditorProps) {
return (
<div id={columnId}>
{hasTabs ? (
<EuiTabs size="s" className="lnsIndexPatternDimensionEditor__header">
<EuiTabs
size="s"
className="lnsIndexPatternDimensionEditor__header"
data-test-subj="lens-dimensionTabs"
>
{supportStaticValue ? (
<EuiTab
isSelected={
Expand Down
Loading

0 comments on commit 40069fe

Please sign in to comment.