Skip to content

Commit

Permalink
[deps] Replace faker with @faker-js (elastic#201105)
Browse files Browse the repository at this point in the history
## Summary

The `faker` library is[ not maintained
anymore](https://fakerjs.dev/about/announcements/2022-01-14.html#i-heard-something-happened-what-s-the-tldr)
and is replaced by a community fork `@faker-js`.
This PR migrates all the usages of faker to the new library, trying to
use the same methods (even if they have slight differences in results
like `faker.random.number()` has a max of 99999 where instead
`faker.number.int()` have a MAX_SAFE_INTEGER as max).
  • Loading branch information
markov00 authored and CAWilson94 committed Dec 12, 2024
1 parent bfa8893 commit 3af2661
Show file tree
Hide file tree
Showing 31 changed files with 122 additions and 130 deletions.
2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -1572,7 +1572,6 @@
"@types/eslint": "^8.44.2",
"@types/express": "^4.17.21",
"@types/extract-zip": "^1.6.2",
"@types/faker": "^5.1.5",
"@types/fetch-mock": "^7.3.1",
"@types/file-saver": "^2.0.0",
"@types/flot": "^0.0.31",
Expand Down Expand Up @@ -1741,7 +1740,6 @@
"expect": "^29.7.0",
"expose-loader": "^0.7.5",
"express": "^4.21.1",
"faker": "^5.1.0",
"fetch-mock": "^7.3.9",
"file-loader": "^4.2.0",
"find-cypress-specs": "^1.41.4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,22 @@

import { calculateWidthFromEntries } from './calculate_width_from_entries';
import { MAX_WIDTH } from './calculate_width_from_char_count';
import faker from 'faker';

const generateLabel = (length: number) => faker.random.alpha({ count: length });
import { faker } from '@faker-js/faker';

const generateObjectWithLabelOfLength = (length: number, propOverrides?: Record<string, any>) => ({
label: generateLabel(length),
label: faker.string.alpha(length),
...propOverrides,
});

describe('calculateWidthFromEntries', () => {
it('calculates width for array of strings', () => {
const shortLabels = [10, 20].map(generateLabel);
const shortLabels = [10, 20].map(faker.string.alpha);
expect(calculateWidthFromEntries(shortLabels)).toBe(256);

const mediumLabels = [50, 55, 10, 20].map(generateLabel);
const mediumLabels = [50, 55, 10, 20].map(faker.string.alpha);
expect(calculateWidthFromEntries(mediumLabels)).toBe(501);

const longLabels = [80, 90, 10].map(generateLabel);
const longLabels = [80, 90, 10].map(faker.string.alpha);
expect(calculateWidthFromEntries(longLabels)).toBe(MAX_WIDTH);
});

Expand All @@ -42,12 +40,12 @@ describe('calculateWidthFromEntries', () => {
});
it('calculates width for array of objects for fallback keys', () => {
const shortLabels = [10, 20].map((v) =>
generateObjectWithLabelOfLength(v, { label: undefined, name: generateLabel(v) })
generateObjectWithLabelOfLength(v, { label: undefined, name: faker.string.alpha(v) })
);
expect(calculateWidthFromEntries(shortLabels, ['id', 'label', 'name'])).toBe(256);

const mediumLabels = [50, 55, 10, 20].map((v) =>
generateObjectWithLabelOfLength(v, { label: undefined, name: generateLabel(v) })
generateObjectWithLabelOfLength(v, { label: undefined, name: faker.string.alpha(v) })
);
expect(calculateWidthFromEntries(mediumLabels, ['id', 'label', 'name'])).toBe(501);
});
Expand Down
4 changes: 2 additions & 2 deletions packages/kbn-dom-drag-drop/src/test_utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*/

import React, { ReactElement } from 'react';
import faker from 'faker';
import { faker } from '@faker-js/faker';
import { RenderOptions, render } from '@testing-library/react';
import { DragContextState, RootDragDropProvider } from './providers';

Expand All @@ -22,7 +22,7 @@ export const dataTransfer = {
};

export const generateDragDropValue = (label = faker.lorem.word()) => ({
id: faker.random.uuid(),
id: faker.string.uuid(),
humanData: {
label,
groupLabel: faker.lorem.word(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
import React from 'react';
import { FieldPicker, FieldPickerProps } from './field_picker';
import { render, screen } from '@testing-library/react';
import faker from 'faker';
import { faker } from '@faker-js/faker';
import userEvent from '@testing-library/user-event';
import { DataType, FieldOptionValue } from './types';

const generateFieldWithLabelOfLength = (length: number) => ({
label: faker.random.alpha({ count: length }),
label: faker.string.alpha(length),
value: {
type: 'field' as const,
field: faker.random.alpha({ count: length }),
field: faker.string.alpha(length),
dataType: 'date' as DataType,
operationType: 'count',
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { CustomPaletteState } from '@kbn/charts-plugin/common/expressions/palett
import { DimensionsVisParam, MetricVisParam } from '../../common';
import { euiThemeVars } from '@kbn/ui-theme';
import { DEFAULT_TRENDLINE_NAME } from '../../common/constants';
import faker from 'faker';
import { faker } from '@faker-js/faker';

const mockDeserialize = jest.fn(({ id }: { id: string }) => {
const convertFn = (v: unknown) => `${id}-${v}`;
Expand Down Expand Up @@ -825,47 +825,47 @@ describe('MetricVisComponent', function () {
// Raw values here, not formatted
const trends: Record<string, MetricWTrend['trend']> = {
Friday: [
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
],
Wednesday: [
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
],
Saturday: [
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
],
Sunday: [
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
],
Thursday: [
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
],
__other__: [
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
],
// this one shouldn't show up!
[DEFAULT_TRENDLINE_NAME]: [
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.random.number(), y: faker.random.number() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
{ x: faker.number.int(), y: faker.number.int() },
],
};

Expand Down Expand Up @@ -1004,7 +1004,7 @@ describe('MetricVisComponent', function () {
});

it('should convert null values to NaN', () => {
const metricId = faker.random.word();
const metricId = faker.lorem.word();

const tableWNull: Datatable = {
type: 'datatable',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
import { createMockBucketColumns, createMockVisData, createMockPieParams } from '../mocks';
import { consolidateMetricColumns } from '../../common/utils';
import { LayerValue } from '@elastic/charts';
import faker from 'faker';
import { faker } from '@faker-js/faker';

const bucketColumns = createMockBucketColumns();
const visData = createMockVisData();
Expand Down Expand Up @@ -186,26 +186,26 @@ describe('getFilterClickData', () => {
const clickedLayers: LayerValue[] = [
{
groupByRollup: 'circle',
value: faker.random.number(),
depth: faker.random.number(),
value: faker.number.int(),
depth: faker.number.int(),
path: [],
sortIndex: faker.random.number(),
sortIndex: faker.number.int(),
smAccessorValue: '',
},
{
groupByRollup: 'green',
value: faker.random.number(),
depth: faker.random.number(),
value: faker.number.int(),
depth: faker.number.int(),
path: [],
sortIndex: faker.random.number(),
sortIndex: faker.number.int(),
smAccessorValue: '',
},
{
groupByRollup: 'metric2',
value: faker.random.number(),
depth: faker.random.number(),
value: faker.number.int(),
depth: faker.number.int(),
path: [],
sortIndex: faker.random.number(),
sortIndex: faker.number.int(),
smAccessorValue: '',
},
];
Expand Down
8 changes: 4 additions & 4 deletions x-pack/plugins/lens/public/app_plugin/app.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import { setState, LensAppState } from '../state_management';
import { coreMock } from '@kbn/core/public/mocks';
import { LensSerializedState } from '..';
import { createMockedField, createMockedIndexPattern } from '../datasources/form_based/mocks';
import faker from 'faker';
import { faker } from '@faker-js/faker';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { VisualizeEditorContext } from '../types';
Expand All @@ -48,7 +48,7 @@ jest.mock('lodash', () => ({
debounce: (fn: unknown) => fn,
}));

const defaultSavedObjectId: string = faker.random.uuid();
const defaultSavedObjectId: string = faker.string.uuid();

const waitToLoad = async () =>
await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
Expand Down Expand Up @@ -233,7 +233,7 @@ describe('Lens App', () => {
});

describe('breadcrumbs', () => {
const breadcrumbDocSavedObjectId = faker.random.uuid();
const breadcrumbDocSavedObjectId = faker.string.uuid();
const breadcrumbDoc = getLensDocumentMock({
savedObjectId: breadcrumbDocSavedObjectId,
title: 'Daaaaaaadaumching!',
Expand Down Expand Up @@ -601,7 +601,7 @@ describe('Lens App', () => {
expect(lensStore.getState().lens.applyChangesCounter).toBe(1);
});
it('adds to the recently accessed list on save', async () => {
const savedObjectId = faker.random.uuid();
const savedObjectId = faker.string.uuid();
await save({ savedObjectId, prevSavedObjectId: 'prevId', comesFromDashboard: false });
expect(services.chrome.recentlyAccessed.add).toHaveBeenCalledWith(
`/app/lens#/edit/${savedObjectId}`,
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/lens/public/app_plugin/app_helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { renderHook, act } from '@testing-library/react-hooks';
import faker from 'faker';
import { faker } from '@faker-js/faker';
import { UseNavigateBackToAppProps, useNavigateBackToApp } from './app_helpers';
import { defaultDoc, makeDefaultServices } from '../mocks/services_mock';
import { cloneDeep } from 'lodash';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { SaveProps } from './app';
import { type SaveVisualizationProps, runSaveLensVisualization } from './save_modal_container';
import { defaultDoc, makeDefaultServices } from '../mocks';
import faker from 'faker';
import { faker } from '@faker-js/faker';
import { makeAttributeService } from '../mocks/services_mock';

jest.mock('../persistence/saved_objects_utils/check_for_duplicate_title', () => ({
Expand Down Expand Up @@ -241,7 +241,7 @@ describe('runSaveLensVisualization', () => {
});
// save the current document as a new by-value copy and add it to a dashboard
it('should save as a new by-value copy and redirect to the dashboard', async () => {
const dashboardId = faker.random.uuid();
const dashboardId = faker.string.uuid();
const { props, saveProps, options, redirectToDashboardFn, saveToLibraryFn, toasts } =
getDefaultArgs(
{
Expand Down Expand Up @@ -271,7 +271,7 @@ describe('runSaveLensVisualization', () => {

// save the current document as a new by-ref copy and add it to a dashboard
it('should save as a new by-ref copy and redirect to the dashboard', async () => {
const dashboardId = faker.random.uuid();
const dashboardId = faker.string.uuid();
const { props, saveProps, options, redirectToDashboardFn, saveToLibraryFn, toasts } =
getDefaultArgs(
{
Expand Down Expand Up @@ -376,7 +376,7 @@ describe('runSaveLensVisualization', () => {
// simulate a new save
const attributeServiceMock = makeAttributeService({
...defaultDoc,
savedObjectId: faker.random.uuid(),
savedObjectId: faker.string.uuid(),
});

const { props, saveProps, options, saveToLibraryFn, cleanupEditor } = getDefaultArgs(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { unifiedSearchPluginMock } from '@kbn/unified-search-plugin/public/mocks
import { IStorageWrapper } from '@kbn/kibana-utils-plugin/public';
import { dataPluginMock } from '@kbn/data-plugin/public/mocks';
import { dataViewPluginMocks } from '@kbn/data-views-plugin/public/mocks';
import faker from 'faker';
import { faker } from '@faker-js/faker';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createMockedIndexPattern } from '../../mocks';
Expand Down Expand Up @@ -402,7 +402,7 @@ describe('percentile', () => {
it('should update order-by references for any terms columns', () => {
const field1 = 'foo';
const field2 = 'bar';
const percentile = faker.random.number(100);
const percentile = faker.number.int(100);

const aggs = [
makeEsAggBuilder('aggTerms', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { DatasourcePublicAPI, SuggestionRequest, DatasourceSuggestion } from '..
import { ChartSwitchProps } from './chart_switch';
import { ChartSwitchPopover } from './chart_switch_popover';
import { LensAppState, applyChanges } from '../../../../state_management';
import faker from 'faker';
import { faker } from '@faker-js/faker';

const mockFrame = (layers: string[]) => ({
...createMockFramePublicAPI(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import React from 'react';
import { screen } from '@testing-library/react';
import faker from 'faker';
import { faker } from '@faker-js/faker';
import {
createMockDatasource,
createMockFramePublicAPI,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { ChildDragDropProvider, Droppable, Draggable } from '@kbn/dom-drag-drop'
import { FramePublicAPI, Visualization, VisualizationConfigProps } from '../../../types';
import { LayerPanel } from './layer_panel';
import { coreMock } from '@kbn/core/public/mocks';
import faker from 'faker';
import { faker } from '@faker-js/faker';
import { generateId } from '../../../id_generator';
import {
createMockVisualization,
Expand Down Expand Up @@ -144,7 +144,7 @@ describe('LayerPanel', () => {
};

beforeEach(() => {
mockVisualization = createMockVisualization(faker.random.alphaNumeric());
mockVisualization = createMockVisualization(faker.string.alphanumeric());
mockVisualization.getLayerIds.mockReturnValue(['first']);
mockDatasource = createMockDatasource();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import { getLensInspectorService } from '../../../lens_inspector_service';
import { inspectorPluginMock } from '@kbn/inspector-plugin/public/mocks';
import { disableAutoApply, enableAutoApply } from '../../../state_management/lens_slice';
import { Ast, toExpression } from '@kbn/interpreter';
import faker from 'faker';
import { faker } from '@faker-js/faker';

const defaultPermissions: Record<string, Record<string, boolean | Record<string, boolean>>> = {
navLinks: { management: true },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { updateVisualizationState, LensAppState } from '../../../state_managemen
import { setChangesApplied } from '../../../state_management/lens_slice';
import { LensInspector } from '../../../lens_inspector_service';
import { screen } from '@testing-library/react';
import faker from 'faker';
import { faker } from '@faker-js/faker';
import { SettingsMenu } from '../../../app_plugin/settings_menu';

describe('workspace_panel_wrapper', () => {
Expand Down Expand Up @@ -98,7 +98,7 @@ describe('workspace_panel_wrapper', () => {
});

it('should render its children', async () => {
const customElementText = faker.random.word();
const customElementText = faker.word.words();
renderWorkspacePanelWrapper({ children: <span>{customElementText}</span> });
expect(screen.getByText(customElementText)).toBeInTheDocument();
});
Expand Down
Loading

0 comments on commit 3af2661

Please sign in to comment.