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

deps: upgrade jest packages to 29.7.0 #16147

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
13 changes: 6 additions & 7 deletions cli/test/cli/bin-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,15 @@
import {pathToFileURL} from 'url';

import * as td from 'testdouble';
import jestMock from 'jest-mock';

import {LH_ROOT} from '../../../shared/root.js';
import {readJson} from '../../../core/test/test-utils.js';
import {fnAny, readJson} from '../../../core/test/test-utils.js';

const mockRunLighthouse = jestMock.fn();
const mockGetFlags = jestMock.fn();
const mockAskPermission = jestMock.fn();
const mockSentryInit = jestMock.fn();
const mockLoggerSetLevel = jestMock.fn();
const mockRunLighthouse = fnAny();
const mockGetFlags = fnAny();
const mockAskPermission = fnAny();
const mockSentryInit = fnAny();
const mockLoggerSetLevel = fnAny();

/** @type {import('../../bin.js')} */
let bin;
Expand Down
13 changes: 6 additions & 7 deletions core/test/config/config-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@
* SPDX-License-Identifier: Apache-2.0
*/

import jestMock from 'jest-mock';

import {Audit as BaseAudit} from '../../audits/audit.js';
import BaseGatherer from '../../gather/base-gatherer.js';
import {initializeConfig, getConfigDisplayString} from '../../config/config.js';
import {LH_ROOT} from '../../../shared/root.js';
import * as format from '../../../shared/localization/format.js';
import defaultConfig from '../../config/default-config.js';
import {nonSimulatedSettingsOverrides} from '../../config/constants.js';
import {fnAny} from '../test-utils.js';

describe('Config', () => {
/** @type {LH.Gatherer.GatherMode} */
Expand Down Expand Up @@ -106,14 +105,14 @@ describe('Config', () => {

it('should throw on invalid artifact definitions', async () => {
const badGatherer = new BaseGatherer();
badGatherer.getArtifact = jestMock.fn();
badGatherer.getArtifact = fnAny();
const config = {artifacts: [{id: 'BadGatherer', gatherer: {instance: badGatherer}}]};
await expect(initializeConfig(gatherMode, config)).rejects.toThrow(/Gatherer for BadGather/);
});

it('should filter configuration by gatherMode', async () => {
const timespanGatherer = new BaseGatherer();
timespanGatherer.getArtifact = jestMock.fn();
timespanGatherer.getArtifact = fnAny();
timespanGatherer.meta = {supportedModes: ['timespan']};

const config = {
Expand Down Expand Up @@ -186,11 +185,11 @@ describe('Config', () => {
beforeEach(() => {
const dependencySymbol = Symbol('dependency');
dependencyGatherer = new BaseGatherer();
dependencyGatherer.getArtifact = jestMock.fn();
dependencyGatherer.getArtifact = fnAny();
dependencyGatherer.meta = {symbol: dependencySymbol, supportedModes: ['snapshot']};
// @ts-expect-error - we satisfy the interface on the next line
dependentGatherer = new BaseGatherer();
dependentGatherer.getArtifact = jestMock.fn();
dependentGatherer.getArtifact = fnAny();
dependentGatherer.meta = {
supportedModes: ['snapshot'],
dependencies: {ImageElements: dependencySymbol},
Expand Down Expand Up @@ -250,7 +249,7 @@ describe('Config', () => {

beforeEach(() => {
const gatherer = new BaseGatherer();
gatherer.getArtifact = jestMock.fn();
gatherer.getArtifact = fnAny();
gatherer.meta = {supportedModes: ['navigation']};

class ExtraAudit extends BaseAudit {
Expand Down
9 changes: 5 additions & 4 deletions core/test/gather/driver/execution-context-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ describe('ExecutionContext', () => {
it('should clear context on frame navigations', async () => {
const executionContext = new ExecutionContext(sessionMock);

const frameListener = sessionMock.on.mock.calls.find(call => call[0] === 'Page.frameNavigated');
expect(frameListener).toBeDefined();
const frameListener = sessionMock.on.mock.calls
.find(call => call[0] === 'Page.frameNavigated') ?? [];
Copy link
Member

Choose a reason for hiding this comment

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

I don't understand this change. The test needs to ensure that frameListener is defined, but it's impossible to be undefined now that you added the ?? [].

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixed

expect(frameListener[1]).toBeDefined();

await forceNewContextId(executionContext, 42);
expect(executionContext.getContextId()).toEqual(42);
Expand All @@ -54,8 +55,8 @@ describe('ExecutionContext', () => {
const executionContext = new ExecutionContext(sessionMock);

const executionDestroyed = sessionMock.on.mock.calls
.find(call => call[0] === 'Runtime.executionContextDestroyed');
expect(executionDestroyed).toBeDefined();
.find(call => call[0] === 'Runtime.executionContextDestroyed') ?? [];
expect(executionDestroyed[1]).toBeDefined();

await forceNewContextId(executionContext, 42);
expect(executionContext.getContextId()).toEqual(42);
Expand Down
2 changes: 1 addition & 1 deletion core/test/gather/driver/target-manager-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ describe('TargetManager', () => {
await targetManager.enable();

expect(sessionMock.on).toHaveBeenCalled();
const sessionListener = sessionMock.on.mock.calls.find(c => c[0] === 'sessionattached')[1];
const sessionListener = sessionMock.on.mock.calls.find(c => c[0] === 'sessionattached')?.[1];

// Original, attach.
expect(sendMock.findAllInvocations('Target.getTargetInfo')).toHaveLength(1);
Expand Down
2 changes: 1 addition & 1 deletion core/test/gather/gatherers/stacks-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import StacksGatherer from '../../../gather/gatherers/stacks.js';
import {fnAny} from '../../test-utils.js';

describe('StacksGatherer', () => {
/** @type {{executionContext: {evaluate: Mock<any, any>}}} */
/** @type {{executionContext: {evaluate: Mock<any>}}} */
let driver;

beforeEach(() => {
Expand Down
14 changes: 9 additions & 5 deletions core/test/gather/mock-commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ function createMockSendCommandFn() {
*/
findInvocation(command) {
expect(mockFn).toHaveBeenCalledWith(command, expect.anything());
return mockFn.mock.calls.find(
call => call[0] === command
)[1];
const call = mockFn.mock.calls.find(call => call[0] === command);
if (!call) throw new Error(`missing invocation for command: ${command}`);
return call[1];
},
/**
* @param {keyof LH.CrdpCommands} command
Expand Down Expand Up @@ -140,7 +140,9 @@ function createMockOnceFn() {
*/
findListener(event) {
expect(mockFn).toHaveBeenCalledWith(event, expect.anything());
return mockFn.mock.calls.find(call => call[0] === event)[1];
const call = mockFn.mock.calls.find(call => call[0] === event);
if (!call) throw new Error(`missing listener for event: ${event}`);
return call[1];
},
/**
* @param {keyof LH.CrdpEvents} event
Expand Down Expand Up @@ -193,7 +195,9 @@ function createMockOnFn() {
*/
findListener(event) {
expect(mockFn).toHaveBeenCalledWith(event, expect.anything());
return mockFn.mock.calls.find(call => call[0] === event)[1];
const call = mockFn.mock.calls.find(call => call[0] === event);
if (!call) throw new Error(`missing listener for event: ${event}`);
return call[1];
},
/**
* @param {keyof LH.CrdpEvents} event
Expand Down
7 changes: 2 additions & 5 deletions core/test/gather/navigation-runner-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
* SPDX-License-Identifier: Apache-2.0
*/

import jestMock from 'jest-mock';

import {
createMockDriver,
createMockBaseArtifacts,
Expand Down Expand Up @@ -33,7 +31,7 @@ const DevtoolsLogGatherer = (await import('../../gather/gatherers/devtools-log.j
const TraceGatherer = (await import('../../gather/gatherers/trace.js')).default;
const {initializeConfig} = await import('../../config/config.js');

/** @typedef {{meta: LH.Gatherer.GathererMeta<'Accessibility'>, getArtifact: Mock<any, any>, startInstrumentation: Mock<any, any>, stopInstrumentation: Mock<any, any>, startSensitiveInstrumentation: Mock<any, any>, stopSensitiveInstrumentation: Mock<any, any>}} MockGatherer */
/** @typedef {{meta: LH.Gatherer.GathererMeta<'Accessibility'>, getArtifact: Mock<any>, startInstrumentation: Mock<any>, stopInstrumentation: Mock<any>, startSensitiveInstrumentation: Mock<any>, stopSensitiveInstrumentation: Mock<any>}} MockGatherer */

describe('NavigationRunner', () => {
let requestedUrl = '';
Expand Down Expand Up @@ -251,8 +249,7 @@ describe('NavigationRunner', () => {
if (!resolvedConfig.artifacts) throw new Error('No artifacts');

const err = new Error('Error in dependency chain');
resolvedConfig.artifacts[0].gatherer.instance.startInstrumentation = jestMock
.fn()
resolvedConfig.artifacts[0].gatherer.instance.startInstrumentation = fnAny()
.mockRejectedValue(err);
resolvedConfig.artifacts[1].dependencies = {Accessibility: {id: 'Timespan'}};
resolvedConfig.artifacts[2].dependencies = {Accessibility: {id: 'Timespan'}};
Expand Down
2 changes: 1 addition & 1 deletion core/test/test-env/mocha-setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ function getSnapshotState(testFile) {
const snapshotDir = path.join(path.dirname(testFile), '__snapshots__');
const snapshotFile = path.join(snapshotDir, path.basename(testFile) + '.snap');
snapshotState = new SnapshotState(snapshotFile, {
rootDir: snapshotDir,
updateSnapshot: process.env.SNAPSHOT_UPDATE ? 'all' : 'none',
prettierPath: '',
snapshotFormat: {},
Expand Down Expand Up @@ -120,7 +121,6 @@ expect.extend({
const context = {snapshotState, currentTestName: title};
// @ts-expect-error - this is enough for snapshots to work.
const matcher = toMatchInlineSnapshot.bind(context);
// @ts-expect-error - not sure why these types are so wrong
const result = matcher(actual, expected);
// @ts-expect-error - not sure why these types are so wrong
if (!result.pass) snapshotTestFailed = true;
Expand Down
12 changes: 7 additions & 5 deletions core/test/test-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ async function makeMocksForGatherRunner() {
});
await td.replaceEsm('../gather/driver/prepare.js', {
prepareTargetForNavigationMode: jestMock.fn(),
prepareTargetForIndividualNavigation: jestMock.fn().mockResolvedValue({warnings: []}),
prepareTargetForIndividualNavigation: fnAny().mockResolvedValue({warnings: []}),
enableAsyncStacks: jestMock.fn().mockReturnValue(jestMock.fn()),
});
await td.replaceEsm('../gather/driver/storage.js', {
Expand All @@ -216,7 +216,7 @@ async function makeMocksForGatherRunner() {
getImportantStorageWarning: jestMock.fn(),
});
await td.replaceEsm('../gather/driver/navigation.js', {
gotoURL: jestMock.fn().mockResolvedValue({
gotoURL: fnAny().mockResolvedValue({
mainDocumentUrl: 'http://example.com',
warnings: [],
}),
Expand All @@ -225,9 +225,11 @@ async function makeMocksForGatherRunner() {

/**
* Same as jestMock.fn(), but uses `any` instead of `unknown`.
* This makes it simpler to override existing properties in test files that are
* typechecked.
*/
const fnAny = () => {
return /** @type {Mock<any, any>} */ (jestMock.fn());
return /** @type {Mock<any>} */ (jestMock.fn());
};

/**
Expand Down Expand Up @@ -288,7 +290,7 @@ function getURLArtifactFromDevtoolsLog(devtoolsLog) {
*
* @param {string} modulePath
* @param {ImportMeta} importMeta
* @return {Promise<Record<string, Mock<any, any>>>}
* @return {Promise<Record<string, Mock<any>>>}
*/
async function importMock(modulePath, importMeta) {
const mock = await import(new URL(modulePath, importMeta.url).href);
Expand All @@ -304,7 +306,7 @@ async function importMock(modulePath, importMeta) {
*
* @param {string} modulePath
* @param {ImportMeta} importMeta
* @return {Record<string, Mock<any, any>>}
* @return {Record<string, Mock<any>>}
*/
function requireMock(modulePath, importMeta) {
const dir = path.dirname(url.fileURLToPath(importMeta.url));
Expand Down
12 changes: 5 additions & 7 deletions core/test/user-flow-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
* SPDX-License-Identifier: Apache-2.0
*/

import jestMock from 'jest-mock';
import * as td from 'testdouble';

import {Runner} from '../runner.js';
import {createMockPage, mockRunnerModule} from './gather/mock-driver.js';
import {fnAny} from './test-utils.js';

const snapshotModule = {snapshotGather: jestMock.fn()};
const snapshotModule = {snapshotGather: fnAny()};
await td.replaceEsm('../gather/snapshot-runner.js', snapshotModule);
const navigationModule = {navigationGather: jestMock.fn()};
const navigationModule = {navigationGather: fnAny()};
await td.replaceEsm('../gather/navigation-runner.js', navigationModule);
const timespanModule = {startTimespanGather: jestMock.fn()};
const timespanModule = {startTimespanGather: fnAny()};
await td.replaceEsm('../gather/timespan-runner.js', timespanModule);

const mockRunner = await mockRunnerModule();
Expand Down Expand Up @@ -68,7 +68,7 @@ describe('UserFlow', () => {
computedCache: new Map(),
},
};
const timespan = {endTimespanGather: jestMock.fn().mockResolvedValue(timespanGatherResult)};
const timespan = {endTimespanGather: fnAny().mockResolvedValue(timespanGatherResult)};
timespanModule.startTimespanGather.mockReset();
timespanModule.startTimespanGather.mockResolvedValue(timespan);
});
Expand Down Expand Up @@ -206,7 +206,6 @@ describe('UserFlow', () => {
let teardownDone = false;
navigationModule.navigationGather.mockImplementation(async (_, cb) => {
setupDone = true;
// @ts-expect-error
await cb();
teardownDone = true;
});
Expand Down Expand Up @@ -238,7 +237,6 @@ describe('UserFlow', () => {

it('should throw errors from the teardown phase', async () => {
navigationModule.navigationGather.mockImplementation(async (_, cb) => {
// @ts-expect-error
await cb();
throw new Error('Teardown Error');
});
Expand Down
2 changes: 1 addition & 1 deletion flow-report/test/setup/env-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const rootHooks = {

// Functions not implemented in JSDOM.
window.Element.prototype.scrollIntoView = jestMock.fn();
global.self.matchMedia = jestMock.fn<any, any>(() => ({
global.self.matchMedia = jestMock.fn<any>(() => ({
addListener: jestMock.fn(),
}));

Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@
"@esbuild-kit/esm-loader": "^2.1.1",
"@esbuild-plugins/node-modules-polyfill": "^0.1.4",
"@formatjs/icu-messageformat-parser": "^2.6.2",
"@jest/fake-timers": "^28.1.0",
"@jest/fake-timers": "^29.7.0",
"@testing-library/preact": "^3.1.1",
"@testing-library/preact-hooks": "^1.1.0",
"@types/archiver": "^2.1.2",
Expand Down Expand Up @@ -155,8 +155,8 @@
"gh-pages": "^2.0.1",
"glob": "^7.1.3",
"idb-keyval": "2.2.0",
"jest-mock": "^27.3.0",
"jest-snapshot": "^28.1.0",
"jest-mock": "^29.7.0",
"jest-snapshot": "^29.7.0",
"jsdom": "^12.2.0",
"lighthouse-plugin-soft-navigation": "^1.0.1",
"magic-string": "^0.25.7",
Expand Down
2 changes: 1 addition & 1 deletion types/internal/test.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

declare global {
var expect: import('expect').Expect;
type Mock<T, Y extends unknown[]> = import('jest-mock').Mock<T, Y>;
type Mock<T> = import('jest-mock').Mock<(...args: any) => T>;
}

declare module 'expect' {
Expand Down
Loading
Loading