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

Consolidates Jest configuration files and scripts #82671

Merged
merged 6 commits into from
Nov 13, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
5 changes: 3 additions & 2 deletions packages/kbn-es-archiver/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"kbn:watch": "rm -rf target && ../../node_modules/.bin/tsc --watch"
},
"dependencies": {
"@kbn/dev-utils": "link:../kbn-dev-utils"
"@kbn/dev-utils": "link:../kbn-dev-utils",
"@kbn/test": "link:../kbn-test"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ exports.getWebpackConfig = function (kibanaPath) {
alias: {
// Dev defaults for test bundle https://github.com/elastic/kibana/blob/6998f074542e8c7b32955db159d15661aca253d7/src/core_plugins/tests_bundle/index.js#L73-L78
fixtures: resolve(kibanaPath, 'src/fixtures'),
test_utils: resolve(kibanaPath, 'src/test_utils/public'),
},
unsafeCache: true,
},
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-i18n/GUIDELINE.md
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ Testing React component that uses the `injectI18n` higher-order component is mor

With shallow rendering only top level component is rendered, that is a wrapper itself, not the original component. Since we want to test the rendering of the original component, we need to access it via the wrapper's `WrappedComponent` property. Its value will be the component we passed into `injectI18n()`.

When testing such component, use the `shallowWithIntl` helper function defined in `test_utils/enzyme_helpers` and pass the component's `WrappedComponent` property to render the wrapped component. This will shallow render the component with Enzyme and inject the necessary context and props to use the `intl` mock defined in `test_utils/mocks/intl`.
When testing such component, use the `shallowWithIntl` helper function defined in `@kbn/test/jest` and pass the component's `WrappedComponent` property to render the wrapped component. This will shallow render the component with Enzyme and inject the necessary context and props to use the `intl` mock defined in `test_utils/mocks/intl`.

Use the `mountWithIntl` helper function to mount render the component.

Expand Down
111 changes: 111 additions & 0 deletions packages/kbn-test/jest-preset.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you 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.
*/

// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html

const { resolve } = require('path');

module.exports = {
// The directory where Jest should output its coverage files
coverageDirectory: '<rootDir>/target/kibana-coverage/jest',

// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: ['/node_modules/', '.*\\.d\\.ts'],

// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: !!process.env.CODE_COVERAGE ? ['json'] : ['html', 'text'],

// An array of file extensions your modules use
moduleFileExtensions: ['js', 'mjs', 'json', 'ts', 'tsx', 'node'],

// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: {
'@elastic/eui/lib/(.*)?': '<rootDir>/node_modules/@elastic/eui/test-env/$1',
'@elastic/eui$': '<rootDir>/node_modules/@elastic/eui/test-env',
'\\.module.(css|scss)$': '<rootDir>/packages/kbn-test/target/jest/mocks/css_module_mock.js',
'\\.(css|less|scss)$': '<rootDir>/packages/kbn-test/target/jest/mocks/style_mock.js',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/packages/kbn-test/target/jest/mocks/file_mock.js',
'\\.ace\\.worker.js$': '<rootDir>/packages/kbn-test/target/jest/mocks/worker_module_mock.js',
'\\.editor\\.worker.js$': '<rootDir>/packages/kbn-test/target/jest/mocks/worker_module_mock.js',
'^(!!)?file-loader!': '<rootDir>/packages/kbn-test/target/jest/mocks/file_mock.js',
'^fixtures/(.*)': '<rootDir>/src/fixtures/$1',
'^src/core/(.*)': '<rootDir>/src/core/$1',
'^src/legacy/(.*)': '<rootDir>/src/legacy/$1',
'^src/plugins/(.*)': '<rootDir>/src/plugins/$1',
},

// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
modulePathIgnorePatterns: ['__fixtures__/', 'target/'],

// Use this configuration option to add custom reporters to Jest
reporters: ['default', resolve(__dirname, './target/jest/junit_reporter')],

// The paths to modules that run some code to configure or set up the testing environment before each test
setupFiles: [
'<rootDir>/packages/kbn-test/target/jest/setup/babel_polyfill.js',
'<rootDir>/packages/kbn-test/target/jest/setup/polyfills.js',
'<rootDir>/packages/kbn-test/target/jest/setup/enzyme.js',
],

// A list of paths to modules that run some code to configure or set up the testing framework before each test
setupFilesAfterEnv: [
'<rootDir>/packages/kbn-test/target/jest/setup/setup_test.js',
'<rootDir>/packages/kbn-test/target/jest/setup/mocks.js',
'<rootDir>/packages/kbn-test/target/jest/setup/react_testing_library.js',
],

// A list of paths to snapshot serializer modules Jest should use for snapshot testing
snapshotSerializers: [
'<rootDir>/src/plugins/kibana_react/public/util/test_helpers/react_mount_serializer.ts',
'<rootDir>/node_modules/enzyme-to-json/serializer',
],

// The test environment that will be used for testing
testEnvironment: 'jest-environment-jsdom-thirteen',

// The glob patterns Jest uses to detect test files
testMatch: ['**/*.test.{js,mjs,ts,tsx}'],

// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
testPathIgnorePatterns: [
'<rootDir>/packages/kbn-ui-framework/(dist|doc_site|generator-kui)/',
'<rootDir>/packages/kbn-pm/dist/',
`integration_tests/`,
],

// This option allows use of a custom test runner
testRunner: 'jest-circus/runner',

// A map from regular expressions to paths to transformers
transform: {
'^.+\\.(js|tsx?)$': '<rootDir>/packages/kbn-test/target/jest/babel_transform.js',
'^.+\\.txt?$': 'jest-raw-loader',
'^.+\\.html?$': 'jest-raw-loader',
},

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
transformIgnorePatterns: [
// ignore all node_modules except monaco-editor which requires babel transforms to handle dynamic import()
// since ESM modules are not natively supported in Jest yet (https://github.com/facebook/jest/issues/4842)
'[/\\\\]node_modules(?![\\/\\\\]monaco-editor)[/\\\\].+\\.js$',
'packages/kbn-pm/dist/index.js',
],
};
4 changes: 4 additions & 0 deletions packages/kbn-test/jest/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"main": "../target/jest",
"types": "../target/types/jest/index.d.ts"
}
14 changes: 10 additions & 4 deletions packages/kbn-test/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,22 @@
"license": "Apache-2.0",
"main": "./target/index.js",
"scripts": {
"build": "../../node_modules/.bin/babel src --out-dir target --delete-dir-on-start --extensions .ts,.js,.tsx --ignore *.test.js,**/__tests__/** --source-maps=inline",
"kbn:bootstrap": "yarn build",
"kbn:watch": "yarn build --watch"
"build": "node scripts/build",
"kbn:bootstrap": "node scripts/build --source-maps",
"kbn:watch": "node scripts/build --watch --source-maps"
},
"kibana": {
"devOnly": true
},
"dependencies": {
"@kbn/es": "link:../kbn-es",
"@kbn/i18n": "link:../kbn-i18n",
"@kbn/optimizer": "link:../kbn-optimizer"
},
"devDependencies": {
"@kbn/babel-preset": "link:../kbn-babel-preset",
"@kbn/dev-utils": "link:../kbn-dev-utils",
"@kbn/expect": "link:../kbn-expect",
"@kbn/utils": "link:../kbn-utils"
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Please install the editorconfig plugin in your editor so that this doesn't keep getting flipped back in forth in every PR

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't believe we have come to a consensus on if we should have newlines or not?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I swapped it because the few I checked had trailing newlines, and I hate seeing the red notice in the Github UI. However, looks like we mostly don't use newlines so I will revert this one.

find packages -name "package.json" | xargs tail -n 1

Copy link
Contributor

Choose a reason for hiding this comment

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

Yeah, it's not exactly enforced but the contributing guides says to install the editorconfig plugin and that config has a rule for package.json specifically (also npm/yarn don't add the extra newline IIRC) https://github.com/elastic/kibana/blob/master/.editorconfig#L11-L14

Copy link
Contributor

Choose a reason for hiding this comment

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

Apparently there is an editorconfig plugin for eslint, so if we wanted to pass those files through eslint too we could, but that's a separate issue.

}
91 changes: 91 additions & 0 deletions packages/kbn-test/scripts/build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you 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.
*/

const { resolve } = require('path');

const del = require('del');
const supportsColor = require('supports-color');
const { run, withProcRunner } = require('@kbn/dev-utils');

const ROOT_DIR = resolve(__dirname, '..');
const BUILD_DIR = resolve(ROOT_DIR, 'target');

const padRight = (width, str) =>
str.length >= width ? str : `${str}${' '.repeat(width - str.length)}`;

run(
async ({ log, flags }) => {
await withProcRunner(log, async (proc) => {
log.info('Deleting old output');
await del(BUILD_DIR);

const cwd = ROOT_DIR;
const env = { ...process.env };
if (supportsColor.stdout) {
env.FORCE_COLOR = 'true';
}

log.info(`Starting babel and typescript${flags.watch ? ' in watch mode' : ''}`);
await Promise.all([
proc.run(padRight(10, `babel`), {
cmd: 'babel',
args: [
'src',
'--config-file',
require.resolve('../babel.config.js'),
'--out-dir',
BUILD_DIR,
'--extensions',
'.ts,.js,.tsx',
...(flags.watch ? ['--watch'] : ['--quiet']),
...(!flags['source-maps'] || !!process.env.CODE_COVERAGE
? []
: ['--source-maps', 'inline']),
],
wait: true,
env,
cwd,
}),

proc.run(padRight(10, 'tsc'), {
cmd: 'tsc',
args: [
...(flags.watch ? ['--watch', '--preserveWatchOutput', 'true'] : []),
...(flags['source-maps'] ? ['--declarationMap', 'true'] : []),
],
wait: true,
env,
cwd,
}),
]);

log.success('Complete');
});
},
{
description: 'Simple build tool for @kbn/i18n package',
flags: {
boolean: ['watch', 'source-maps'],
help: `
--watch Run in watch mode
--source-maps Include sourcemaps
`,
},
}
);
2 changes: 0 additions & 2 deletions packages/kbn-test/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,3 @@ export { runFailedTestsReporterCli } from './failed_tests_reporter';
export { CI_PARALLEL_PROCESS_PREFIX } from './ci_parallel_process_prefix';

export * from './functional_test_runner';

export * from './jest';
4 changes: 1 addition & 3 deletions packages/kbn-test/src/jest/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,4 @@
* under the License.
*/

export * from './junit_reporter';

export * from './report_path';
export * from './utils';
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { readFileSync } from 'fs';
import del from 'del';
import execa from 'execa';
import xml2js from 'xml2js';
import { getUniqueJunitReportPath } from '@kbn/test';
import { getUniqueJunitReportPath } from '../../report_path';
import { REPO_ROOT } from '@kbn/utils';

const MINUTE = 1000 * 60;
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-test/src/jest/junit_reporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import type { Config } from '@jest/types';
import { AggregatedResult, Test, BaseReporter } from '@jest/reporters';

import { escapeCdata } from '../mocha/xml';
import { getUniqueJunitReportPath } from './report_path';
import { getUniqueJunitReportPath } from '../report_path';

interface ReporterOptions {
reportName?: string;
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,11 @@ const MutationObserver = require('mutation-observer');
Object.defineProperty(window, 'MutationObserver', { value: MutationObserver });

require('whatwg-fetch');

if (!global.URL.hasOwnProperty('createObjectURL')) {
Object.defineProperty(global.URL, 'createObjectURL', { value: () => '' });
}

// Will be replaced with a better solution in EUI
// https://github.com/elastic/eui/issues/3713
global._isJest = true;
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,14 @@
* under the License.
*/

export { findTestSubject } from './find_test_subject';
export function test(value: any) {
return value && value.__reactMount__;
}

export { WithStore } from './redux_helpers';

export { WithMemoryRouter, WithRoute, reactRouterMock } from './router_helpers';

export * from './utils';

export {
setSVGElementGetBBox,
setHTMLElementOffset,
setHTMLElementClientSizes,
setSVGElementGetComputedTextLength,
} from './jsdom_svg_mocks';
export function print(value: any, serialize: any) {
// there is no proper way to correctly indent multiline values
// so the trick here is to use the Object representation and rewriting the root object name
return serialize({
reactNode: value.__reactMount__,
}).replace('Object', 'MountPoint');
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@
* under the License.
*/

export {
setSVGElementGetBBox,
setHTMLElementOffset,
setHTMLElementClientSizes,
setSVGElementGetComputedTextLength,
} from './helpers';
/*
Global import, so we don't need to remember to import the lib in each file
https://www.npmjs.com/package/jest-styled-components#global-installation
*/

import 'jest-styled-components';
import '@testing-library/jest-dom';
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
/*
* 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.
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you 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.
*/

/**
Expand Down Expand Up @@ -192,4 +205,14 @@ export const mountHook = <Args extends {}, HookValue extends any>(
};
};

export const nextTick = () => new Promise((res) => process.nextTick(res));
export function shallowWithI18nProvider<T>(child: ReactElement<T>) {
const wrapped = shallow(<I18nProvider>{child}</I18nProvider>);
const name = typeof child.type === 'string' ? child.type : child.type.name;
return wrapped.find(name).dive();
}

export function mountWithI18nProvider<T>(child: ReactElement<T>) {
const wrapped = mount(<I18nProvider>{child}</I18nProvider>);
const name = typeof child.type === 'string' ? child.type : child.type.name;
return wrapped.find(name);
}
Loading