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

tests: sequester mocks to -test.mocks.js files #14216

Closed
wants to merge 29 commits into from
Closed
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
b00625a
tests: use workers and Mocha node api instead of calling the CLI
connorjclark Jul 14, 2022
70ae6a5
force in process when just one test
connorjclark Jul 14, 2022
a7faedc
comment about parallel mode
connorjclark Jul 14, 2022
ae5da3f
pass bail thru
connorjclark Jul 14, 2022
09a5189
remove old baseArgs stuff
connorjclark Jul 14, 2022
5680cc3
log error
connorjclark Jul 14, 2022
5076b65
fix snapshot update
connorjclark Jul 14, 2022
91e35cf
fix unit flow
connorjclark Jul 15, 2022
0de0320
fix fetcher test
connorjclark Jul 15, 2022
a95659c
oof forgot to exit in worker
connorjclark Jul 15, 2022
db293b2
wip: .mocks test files
connorjclark Jul 15, 2022
22b6724
fix unit flow lol
connorjclark Jul 15, 2022
64a4a75
user-flow-test.js
connorjclark Jul 15, 2022
2d75f0b
snapshot-runner-test.mocks.js
connorjclark Jul 15, 2022
3b7e7b6
timespan-runner-test.mocks.js
connorjclark Jul 15, 2022
40925b2
navigation-test.js ugh
connorjclark Jul 15, 2022
e5db1f6
prepare-test.js
connorjclark Jul 15, 2022
d459cea
link-elements-test.js
connorjclark Jul 15, 2022
e2a2fa9
script-elements-test.js
connorjclark Jul 15, 2022
b59d133
service-worker-test.js
connorjclark Jul 15, 2022
1a390d7
response-compression-test.js
connorjclark Jul 15, 2022
35f354a
bin-test.js
connorjclark Jul 16, 2022
1f6bd56
Merge remote-tracking branch 'origin/master' into mocks-files
connorjclark Jul 18, 2022
e63e384
fix the worst mock shennanigans evers
connorjclark Jul 18, 2022
ed5911a
tsc
connorjclark Jul 18, 2022
e758655
Merge remote-tracking branch 'origin/main' into mocks-files
connorjclark Oct 24, 2022
b557fa0
Merge remote-tracking branch 'origin/main' into mocks-files
connorjclark Oct 24, 2022
da8a4d7
fix merge
connorjclark Oct 24, 2022
564c542
hmm
connorjclark Oct 24, 2022
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
12 changes: 6 additions & 6 deletions flow-report/test/run-flow-report-tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@

set -eux

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
LH_ROOT="$SCRIPT_DIR/../.."

ARGS=(
--testMatch='{flow-report/**/*-test.ts,flow-report/**/*-test.tsx}'
--require=flow-report/test/setup/env-setup.ts
--loader=@esbuild-kit/esm-loader
# util-test.tsx won't finish on its own because of an open MessagePort, so help it out.
# See https://github.com/jsdom/jsdom/issues/2448#issuecomment-802288244
--exit
--require="$LH_ROOT/flow-report/test/setup/env-setup.ts"
)

yarn mocha ${ARGS[*]} "$@"
cd "$LH_ROOT"
node --loader=@esbuild-kit/esm-loader lighthouse-core/test/scripts/run-mocha-tests.js ${ARGS[*]} "$@"
57 changes: 30 additions & 27 deletions flow-report/test/setup/env-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,32 +21,35 @@ fs.writeFileSync(`${LH_ROOT}/node_modules/@testing-library/preact/dist/esm/packa
fs.writeFileSync(`${LH_ROOT}/node_modules/@testing-library/preact-hooks/src/package.json`,
'{"type": "module"}');

// @ts-expect-error
global.React = preact;

export default {
mochaHooks: {
beforeEach() {
const {window} = new JSDOM(undefined, {
url: 'file:///Users/example/report.html/',
});
global.window = window as any;
global.document = window.document;
global.location = window.location;
global.self = global.window;

// Use JSDOM types as necessary.
global.Blob = window.Blob;
global.HTMLInputElement = window.HTMLInputElement;

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

// @ts-expect-error: for @testing-library/preact-hooks
global.MessageChannel = MessageChannel;
},
const rootHooks = {
beforeAll() {
// @ts-expect-error
global.React = preact;
},
beforeEach() {
const {window} = new JSDOM(undefined, {
url: 'file:///Users/example/report.html/',
});
global.window = window as any;
global.document = window.document;
global.location = window.location;
global.self = global.window;

// Use JSDOM types as necessary.
global.Blob = window.Blob;
global.HTMLInputElement = window.HTMLInputElement;

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

// @ts-expect-error: for @testing-library/preact-hooks
global.MessageChannel = MessageChannel;
},
};

export {
rootHooks,
};
16 changes: 5 additions & 11 deletions lighthouse-core/test/fraggle-rock/gather/navigation-runner-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import jestMock from 'jest-mock';
import {
createMockDriver,
createMockBaseArtifacts,
mockDriverSubmodules,
mockRunnerModule,
} from './mock-driver.js';
import {initializeConfig} from '../../../fraggle-rock/config/config.js';
import {defaultNavigationConfig} from '../../../config/constants.js';
Expand All @@ -19,21 +17,17 @@ import DevtoolsLogGatherer from '../../../gather/gatherers/devtools-log.js';
import TraceGatherer from '../../../gather/gatherers/trace.js';
import {fnAny} from '../../test-utils.js';
import {networkRecordsToDevtoolsLog} from '../../network-records-to-devtools-log.js';
import {Runner as runnerActual} from '../../../runner.js';
import * as runner from '../../../fraggle-rock/gather/navigation-runner.js';

// Some imports needs to be done dynamically, so that their dependencies will be mocked.
// See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs
// https://github.com/facebook/jest/issues/10025
/** @type {import('../../../fraggle-rock/gather/navigation-runner.js')} */
let runner;
/** @type {import('./navigation-runner-test.mocks.js').testContext} */
// @ts-expect-error
const testContext = global.lighthouseTestContext;
const {mocks, mockRunner, runnerActual} = testContext;

const mocks = await mockDriverSubmodules();
const mockRunner = await mockRunnerModule();
beforeEach(async () => {
mockRunner.reset();
mockRunner.getGathererList.mockImplementation(runnerActual.getGathererList);
mockRunner.getAuditList.mockImplementation(runnerActual.getAuditList);
runner = (await import('../../../fraggle-rock/gather/navigation-runner.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 */
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @license Copyright 2022 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

import {Runner} from '../../../runner.js';
import {
mockDriverSubmodules,
mockRunnerModule,
} from './mock-driver.js';

const mocks = await mockDriverSubmodules();
const mockRunner = await mockRunnerModule();

mockRunner.getGathererList.mockImplementation(Runner.getGathererList);
mockRunner.getAuditList.mockImplementation(Runner.getAuditList);

/** @typedef {typeof testContext} testContext */
const testContext = {
mocks,
mockRunner,
runnerActual: Runner,
};
export {testContext};
17 changes: 2 additions & 15 deletions lighthouse-core/test/gather/fetcher-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,13 @@
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

import {Fetcher} from '../../gather/fetcher.js';
import {Driver} from '../../gather/driver.js';
import {Connection} from '../../gather/connections/connection.js';
import {fnAny, mockCommands} from '../test-utils.js';

const {createMockSendCommandFn} = mockCommands;

// Some imports needs to be done dynamically, so that their dependencies will be mocked.
// See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs
// https://github.com/facebook/jest/issues/10025
/** @typedef {import('../../gather/driver.js').Driver} Driver */
/** @type {typeof import('../../gather/driver.js').Driver} */
let Driver;
/** @typedef {import('../../gather/fetcher.js').Fetcher} Fetcher */
/** @type {typeof import('../../gather/fetcher.js').Fetcher} */
let Fetcher;

before(async () => {
Driver = (await import('../../gather/driver.js')).Driver;
Fetcher = (await import('../../gather/fetcher.js')).Fetcher;
});

/** @type {Connection} */
let connectionStub;
/** @type {Driver} */
Expand Down
24 changes: 3 additions & 21 deletions lighthouse-core/test/gather/gather-runner-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@ import {strict as assert} from 'assert';
import jestMock from 'jest-mock';

import {Gatherer} from '../../gather/gatherers/gatherer.js';
// import GathererRunner_ from '../../gather/gather-runner.js';
// import {Config} from '../../config/config.js';
import {GatherRunner as GatherRunner_} from '../../gather/gather-runner.js';
import {Config} from '../../config/config.js';
import {LighthouseError} from '../../lib/lh-error.js';
import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js';
// import {Driver} from '../../gather/driver.js';
import {Driver} from '../../gather/driver.js';
import {Connection} from '../../gather/connections/connection.js';
import {createMockSendCommandFn, createMockOnceFn} from './mock-commands.js';
import {
makeMocksForGatherRunner,
makeParamsOptional,
makePromiseInspectable,
flushAllTimersAndMicrotasks,
Expand All @@ -30,8 +29,6 @@ import {fakeDriver} from './fake-driver.js';

const unresolvedPerfLog = readJson('./../fixtures/unresolved-perflog.json', import.meta);

await makeMocksForGatherRunner();

/** @type {jestMock.SpyInstance<Promise<void>, [session: any, pageUrl: string]>} */
let assertNoSameOriginServiceWorkerClientsMock;

Expand All @@ -49,24 +46,9 @@ function createTypeHackedGatherRunner() {
};
}

// Some imports needs to be done dynamically, so that their dependencies will be mocked.
// See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs
// https://github.com/facebook/jest/issues/10025
/** @typedef {import('../../gather/driver.js').Driver} Driver */
/** @type {typeof import('../../gather/driver.js').Driver} */
let Driver;
/** @type {typeof import('../../gather/gather-runner.js').GatherRunner} */
let GatherRunner_;
/** @typedef {import('../../config/config.js').Config} Config */
/** @type {typeof import('../../config/config.js').Config} */
let Config;

/** @type {ReturnType<createTypeHackedGatherRunner>} */
let GatherRunner;
before(async () => {
Driver = (await import('../../gather/driver.js')).Driver;
GatherRunner_ = (await import('../../gather/gather-runner.js')).GatherRunner;
Config = (await import('../../config/config.js')).Config;
assertNoSameOriginServiceWorkerClientsMock =
jestMock.spyOn(GatherRunner_, 'assertNoSameOriginServiceWorkerClients');
GatherRunner = createTypeHackedGatherRunner();
Expand Down
9 changes: 9 additions & 0 deletions lighthouse-core/test/gather/gather-runner-test.mocks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* @license Copyright 2022 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

import {makeMocksForGatherRunner} from '../test-utils.js';

await makeMocksForGatherRunner();
47 changes: 8 additions & 39 deletions lighthouse-core/test/runner-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,62 +9,31 @@ import {strict as assert} from 'assert';
import path from 'path';

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

// import Runner from '../runner.js';
// import {GatherRunner} from '../gather/gather-runner.js';
import {Runner} from '../runner.js';
import {GatherRunner} from '../gather/gather-runner.js';
import {fakeDriver as driverMock} from './gather/fake-driver.js';
// import {Config} from '../config/config.js';
import {Config} from '../config/config.js';
import {Audit} from '../audits/audit.js';
import {Gatherer} from '../gather/gatherers/gatherer.js';
import * as assetSaver from '../lib/asset-saver.js';
import {LighthouseError} from '../lib/lh-error.js';
import * as i18n from '../lib/i18n/i18n.js';
import {importMock, makeMocksForGatherRunner} from './test-utils.js';
import {importMock} from './test-utils.js';
import {getModuleDirectory} from '../../esm-utils.js';

const moduleDir = getModuleDirectory(import.meta);

await makeMocksForGatherRunner();
/** @type {import('./runner-test.mocks.js').testContext} */
// @ts-expect-error
const testContext = global.lighthouseTestContext;
const {saveArtifactsSpy, saveLhrSpy, loadArtifactsSpy} = testContext;

// Some imports needs to be done dynamically, so that their dependencies will be mocked.
// See: https://jestjs.io/docs/ecmascript-modules#differences-between-esm-and-commonjs
// https://github.com/facebook/jest/issues/10025
/** @type {typeof import('../runner.js').Runner} */
let Runner;
/** @type {typeof import('../gather/gather-runner.js').GatherRunner} */
let GatherRunner;
/** @type {typeof import('../config/config.js').Config} */
let Config;

/** @type {jestMock.Mock} */
let saveArtifactsSpy;
/** @type {jestMock.Mock} */
let saveLhrSpy;
/** @type {jestMock.Mock} */
let loadArtifactsSpy;
/** @type {jestMock.Mock} */
let gatherRunnerRunSpy;
/** @type {jestMock.Mock} */
let runAuditSpy;

await td.replaceEsm('../lib/asset-saver.js', {
saveArtifacts: saveArtifactsSpy = jestMock.fn(assetSaver.saveArtifacts),
saveLhr: saveLhrSpy = jestMock.fn(),
loadArtifacts: loadArtifactsSpy = jestMock.fn(assetSaver.loadArtifacts),
});

await td.replaceEsm('../gather/driver/service-workers.js', {
getServiceWorkerVersions: jestMock.fn().mockResolvedValue({versions: []}),
getServiceWorkerRegistrations: jestMock.fn().mockResolvedValue({registrations: []}),
});

before(async () => {
Runner = (await import('../runner.js')).Runner;
GatherRunner = (await import('../gather/gather-runner.js')).GatherRunner;
Config = (await import('../config/config.js')).Config;
});

beforeEach(() => {
gatherRunnerRunSpy = jestMock.spyOn(GatherRunner, 'run');
runAuditSpy = jestMock.spyOn(Runner, '_runAudit');
Expand Down
39 changes: 39 additions & 0 deletions lighthouse-core/test/runner-test.mocks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* @license Copyright 2022 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

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

import {makeMocksForGatherRunner} from './test-utils.js';
import * as assetSaver from '../lib/asset-saver.js';

await makeMocksForGatherRunner();

/** @type {jestMock.Mock} */
let saveArtifactsSpy;
/** @type {jestMock.Mock} */
let saveLhrSpy;
/** @type {jestMock.Mock} */
let loadArtifactsSpy;

await td.replaceEsm('../lib/asset-saver.js', {
saveArtifacts: saveArtifactsSpy = jestMock.fn(assetSaver.saveArtifacts),
saveLhr: saveLhrSpy = jestMock.fn(),
loadArtifacts: loadArtifactsSpy = jestMock.fn(assetSaver.loadArtifacts),
});

await td.replaceEsm('../gather/driver/service-workers.js', {
getServiceWorkerVersions: jestMock.fn().mockResolvedValue({versions: []}),
getServiceWorkerRegistrations: jestMock.fn().mockResolvedValue({registrations: []}),
});

/** @typedef {typeof testContext} testContext */
const testContext = {
saveArtifactsSpy,
saveLhrSpy,
loadArtifactsSpy,
};
export {testContext};
Loading