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

Update jest (main) #173227

Merged
merged 18 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from 17 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
28 changes: 14 additions & 14 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -1292,10 +1292,10 @@
"@frsource/cypress-plugin-visual-regression-diff": "^3.3.10",
"@istanbuljs/nyc-config-typescript": "^1.0.2",
"@istanbuljs/schema": "^0.1.2",
"@jest/console": "^29.6.1",
"@jest/reporters": "^29.6.1",
"@jest/console": "^29.7.0",
"@jest/reporters": "^29.7.0",
"@jest/transform": "^29.6.1",
"@jest/types": "^29.6.1",
"@jest/types": "^29.6.3",
"@kayahr/text-encoding": "^1.3.0",
"@kbn/alerting-api-integration-helpers": "link:x-pack/test/alerting_api_integration/packages/helpers",
"@kbn/ambient-common-types": "link:packages/kbn-ambient-common-types",
Expand Down Expand Up @@ -1628,7 +1628,7 @@
"argsplit": "^1.0.5",
"autoprefixer": "^10.4.7",
"axe-core": "^4.10.0",
"babel-jest": "^29.6.1",
"babel-jest": "^29.7.0",
"babel-loader": "^8.2.5",
"babel-plugin-add-module-exports": "^1.0.4",
"babel-plugin-istanbul": "^6.1.1",
Expand Down Expand Up @@ -1682,7 +1682,7 @@
"eslint-plugin-react-perf": "^3.3.1",
"eslint-traverse": "^1.0.0",
"exit-hook": "^2.2.0",
"expect": "^29.6.1",
"expect": "^29.7.0",
"expose-loader": "^0.7.5",
"express": "^4.19.2",
"faker": "^5.1.0",
Expand All @@ -1701,16 +1701,16 @@
"http2-proxy": "^5.0.53",
"http2-wrapper": "^2.2.1",
"ignore": "^5.3.0",
"jest": "^29.6.1",
"jest": "^29.7.0",
"jest-canvas-mock": "^2.5.2",
"jest-cli": "^29.6.1",
"jest-config": "^29.6.1",
"jest-diff": "^29.6.1",
"jest-environment-jsdom": "^29.6.1",
"jest-matcher-utils": "^29.6.1",
"jest-mock": "^29.6.1",
"jest-runtime": "^29.6.1",
"jest-snapshot": "^29.6.1",
"jest-cli": "^29.7.0",
"jest-config": "^29.7.0",
"jest-diff": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"jest-matcher-utils": "^29.7.0",
"jest-mock": "^29.7.0",
"jest-runtime": "^29.7.0",
"jest-snapshot": "^29.7.0",
"jest-specific-snapshot": "^8.0.0",
"jest-styled-components": "7.0.3",
"jsdom": "^20.0.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ const roleEditor = 'editor';
const cloudUsersFilePath = resolve(REPO_ROOT, SERVERLESS_ROLES_ROOT_PATH, 'role_users.json');

const createLocalSAMLSessionMock = jest.spyOn(samlAuth, 'createLocalSAMLSession');
const createCloudSAMLSessionMock = jest.spyOn(samlAuth, 'createCloudSAMLSession');
const getSecurityProfileMock = jest.spyOn(samlAuth, 'getSecurityProfile');
const readCloudUsersFromFileMock = jest.spyOn(helper, 'readCloudUsersFromFile');
const isValidHostnameMock = jest.spyOn(helper, 'isValidHostname');
Expand All @@ -41,6 +40,11 @@ jest.mock('../kbn_client/kbn_client', () => {
const get = jest.fn();

describe('SamlSessionManager', () => {
let createCloudSAMLSessionMock: jest.SpyInstance;
beforeEach(() => {
createCloudSAMLSessionMock = jest.spyOn(samlAuth, 'createCloudSAMLSession');
});
Comment on lines +43 to +46
Copy link
Member

@dmlemeshko dmlemeshko Aug 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@afharo totally fine with the change, but could you explain why it is required after update?
Is there something specific about createCloudSAMLSession function?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't find anything in the changelogs, but my observation in this PR is that jest changed (broke? 🤷) how spies are reset via the jest.reset/restoreAllMocks and the specific myMock.mockReset/Restore.

This means the pattern global spy + jest.reset/restoreAllMocks didn't work in some cases. I found that recreating the spy on each run was more stable (but lazy me, only changed it for those breaking the tests 😇)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only changed it for those breaking the tests

Thank you! I will update other tests later.


describe('for local session', () => {
beforeEach(() => {
jest.resetAllMocks();
Expand Down Expand Up @@ -199,6 +203,7 @@ describe('SamlSessionManager', () => {
});

test('should throw error if TEST_CLOUD_HOST_NAME is not set', async () => {
createCloudSAMLSessionMock.mockRestore();
isValidHostnameMock.mockReturnValueOnce(false);
const samlSessionManager = new SamlSessionManager(samlSessionManagerOptions);
await expect(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ describe('Elasticsearch blob storage', () => {
esBlobStorage = createEsBlobStorage({ chunkSize: '1024B' });
const { id } = await esBlobStorage.upload(Readable.from([fileString]));
expect(await getAllDocCount()).toMatchObject({ count: 37 });
esRefreshIndexSpy.mockReset();
esRefreshIndexSpy.mockClear();
const rs = await esBlobStorage.download({ id });
expect(esRefreshIndexSpy).toHaveBeenCalled(); // Make sure we refresh the index before downloading the chunks
const chunks: string[] = [];
Expand Down Expand Up @@ -141,7 +141,7 @@ describe('Elasticsearch blob storage', () => {
const { id } = await esBlobStorage.upload(Readable.from([fileString]));
const { id: id2 } = await esBlobStorage.upload(Readable.from([fileString2]));
expect(await getAllDocCount()).toMatchObject({ count: 10 });
esRefreshIndexSpy.mockReset();
esRefreshIndexSpy.mockClear();
await esBlobStorage.delete(id);
expect(esRefreshIndexSpy).toHaveBeenCalled(); // Make sure we refresh the index before deleting the chunks
expect(await getAllDocCount()).toMatchObject({ count: 2 });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,9 @@ describe('convertToPercentileColumns', () => {
if (expected === null) {
expect(convertToPercentileColumns(...input)).toBeNull();
} else if (Array.isArray(expected)) {
expect(convertToPercentileColumns(...input)).toEqual(expected.map(expect.objectContaining));
expect(convertToPercentileColumns(...input)).toEqual(
expected.map((el) => (el === null ? null : expect.objectContaining(el)))
);
} else {
expect(convertToPercentileColumns(...input)).toEqual(expect.objectContaining(expected));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ describe('convertToPercentileRankColumns', () => {
expect(convertToPercentileRankColumns(...input)).toBeNull();
} else if (Array.isArray(expected)) {
expect(convertToPercentileRankColumns(...input)).toEqual(
expected.map(expect.objectContaining)
expected.map((el) => (el === null ? null : expect.objectContaining(el)))
);
} else {
expect(convertToPercentileRankColumns(...input)).toEqual(expect.objectContaining(expected));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ beforeAll(() => {
beforeEach(() => {
clock.reset();
jest.resetAllMocks();
jest.restoreAllMocks();
connectorTokenClient = new ConnectorTokenClient({
unsecuredSavedObjectsClient,
encryptedSavedObjectsClient,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ describe('Task Runner', () => {

beforeEach(() => {
jest.resetAllMocks();
jest.restoreAllMocks(); // clear spy mock implementations
logger.isLevelEnabled.mockReturnValue(true);
jest
.requireMock('../lib/wrap_scoped_cluster_client')
Expand Down Expand Up @@ -1969,7 +1970,7 @@ describe('Task Runner', () => {
});

test('should set unexpected errors as framework-error', async () => {
(getExecutorServicesModule.getExecutorServices as jest.Mock).mockImplementation(() => {
jest.spyOn(getExecutorServicesModule, 'getExecutorServices').mockImplementation(() => {
throw new Error('test');
});

Expand Down
18 changes: 13 additions & 5 deletions x-pack/plugins/fleet/server/services/fleet_server/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import { elasticsearchServiceMock } from '@kbn/core-elasticsearch-server-mocks';
import { savedObjectsClientMock } from '@kbn/core-saved-objects-api-server-mocks';

import type { PackagePolicy } from '../../../common';

import { appContextService } from '..';

import type { MockedFleetAppContext } from '../../mocks';
Expand All @@ -24,7 +26,6 @@ import {
} from '.';

jest.mock('../agent_policy');
jest.mock('../package_policy');
jest.mock('../agents');

const mockedAgentPolicyService = agentPolicyService as jest.Mocked<typeof agentPolicyService>;
Expand Down Expand Up @@ -54,7 +55,8 @@ describe('checkFleetServerVersionsForSecretsStorage', () => {
it('should return true if all fleet server versions are at least the specified version and there are no managed policies', async () => {
const version = '1.0.0';

mockedPackagePolicyService.list
jest
.spyOn(mockedPackagePolicyService, 'list')
.mockResolvedValueOnce({
items: [
{
Expand Down Expand Up @@ -162,7 +164,7 @@ describe('getFleetServerPolicies', () => {
policy_id: 'agent-policy-2',
policy_ids: ['agent-policy-2'],
},
];
] as PackagePolicy[];
const mockFleetServerPolicies = [
{
id: 'fs-policy-1',
Expand All @@ -185,16 +187,22 @@ describe('getFleetServerPolicies', () => {
];

it('should return no policies if there are no fleet server package policies', async () => {
(mockedPackagePolicyService.list as jest.Mock).mockResolvedValueOnce({
jest.spyOn(mockedPackagePolicyService, 'list').mockResolvedValueOnce({
items: [],
total: 0,
page: 1,
perPage: 10,
});
const result = await getFleetServerPolicies(soClient);
expect(result).toEqual([]);
});

it('should return agent policies with fleet server package policies', async () => {
(mockedPackagePolicyService.list as jest.Mock).mockResolvedValueOnce({
jest.spyOn(mockedPackagePolicyService, 'list').mockResolvedValueOnce({
items: mockPackagePolicies,
total: mockPackagePolicies.length,
page: 1,
perPage: mockPackagePolicies.length,
});
(mockedAgentPolicyService.getByIDs as jest.Mock).mockResolvedValueOnce(mockFleetServerPolicies);
const result = await getFleetServerPolicies(soClient);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ describe('SyntheticsService', () => {
describe('getSyntheticsParams', () => {
it('returns the params for all spaces', async () => {
const { service } = getMockedService();
jest.spyOn(service, 'getSyntheticsParams').mockReset();
jest.spyOn(service, 'getSyntheticsParams').mockRestore();

(axios as jest.MockedFunction<typeof axios>).mockResolvedValue({} as AxiosResponse);

Expand All @@ -416,7 +416,7 @@ describe('SyntheticsService', () => {

it('returns the params for specific space', async () => {
const { service } = getMockedService();
jest.spyOn(service, 'getSyntheticsParams').mockReset();
jest.spyOn(service, 'getSyntheticsParams').mockRestore();

serverMock.encryptedSavedObjects = mockEncryptedSO({
params: [
Expand All @@ -440,7 +440,7 @@ describe('SyntheticsService', () => {
});
it('returns the space limited params', async () => {
const { service } = getMockedService();
jest.spyOn(service, 'getSyntheticsParams').mockReset();
jest.spyOn(service, 'getSyntheticsParams').mockRestore();

serverMock.encryptedSavedObjects = mockEncryptedSO({
params: [
Expand Down
5 changes: 5 additions & 0 deletions x-pack/plugins/reporting/server/lib/content_stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ describe('ContentStream', () => {
);
});

afterEach(() => {
stream.destroy();
base64Stream.destroy();
});

describe('read', () => {
it('should perform a search using index and the document id', async () => {
await new Promise((resolve) => stream.once('data', resolve));
Expand Down
Loading