[Maps] Do not mutate state in resetDataRequest (#55624)

This commit is contained in:
Thomas Neirynck 2020-01-24 10:58:14 -05:00 committed by GitHub
parent f7c53b5690
commit 5c19f9db4e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 74 additions and 6 deletions

View file

@ -447,16 +447,28 @@ function updateWithDataResponse(state, action) {
return resetDataRequest(state, action, dataRequest);
}
function resetDataRequest(state, action, request) {
export function resetDataRequest(state, action, request) {
const dataRequest = request || getValidDataRequest(state, action);
if (!dataRequest) {
return state;
}
dataRequest.dataRequestToken = null;
dataRequest.dataId = action.dataId;
const layerList = [...state.layerList];
return { ...state, layerList };
const layer = findLayerById(state, action.layerId);
const dataRequestIndex = layer.__dataRequests.indexOf(dataRequest);
const newDataRequests = [...layer.__dataRequests];
newDataRequests[dataRequestIndex] = {
...dataRequest,
dataRequestToken: null,
};
const layerIndex = state.layerList.indexOf(layer);
const newLayerList = [...state.layerList];
newLayerList[layerIndex] = {
...layer,
__dataRequests: newDataRequests,
};
return { ...state, layerList: newLayerList };
}
function getValidDataRequest(state, action, checkRequestToken = true) {

View file

@ -0,0 +1,56 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
jest.mock('../actions/map_actions', () => ({}));
import { resetDataRequest } from './map';
import _ from 'lodash';
describe('reducers/map', () => {
it('Should clear datarequest without mutation store state', async () => {
const layerId = 'foobar';
const requestToken = 'tokenId';
const dataId = 'dataId';
const preState = {
layerList: [
{
id: `not_${layerId}`,
},
{
id: layerId,
__dataRequests: [
{
dataRequestToken: `not_${requestToken}`,
dataId: `not_${dataId}`,
},
{
dataRequestToken: requestToken,
dataId: dataId,
},
],
},
],
};
const preStateCopy = _.cloneDeep(preState);
const action = {
layerId,
requestToken,
dataId,
};
const postState = resetDataRequest(preState, action);
//Ensure previous state is not mutated.
expect(_.isEqual(preState, preStateCopy)).toEqual(true);
//Ensure new state is set correctly.
expect(postState.layerList[1].__dataRequests[1].dataId).toEqual(dataId);
expect(postState.layerList[1].__dataRequests[1].dataRequestToken).toEqual(null);
});
});

View file

@ -6,7 +6,7 @@
import { copyPersistentState } from './util';
describe('store/util', () => {
describe('reducers/util', () => {
describe('copyPersistentState', () => {
it('should ignore state preceded by double underscores', async () => {
const copy = copyPersistentState({