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

feat: add support for .mjs config #9431

Merged
merged 9 commits into from
Jan 21, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- `[jest-config]` [**BREAKING**] Set default display name color based on runner ([#8689](https://github.com/facebook/jest/pull/8689))
- `[jest-config]` Merge preset globals with project globals ([#9027](https://github.com/facebook/jest/pull/9027))
- `[jest-config]` Support `.cjs` config files ([#9291](https://github.com/facebook/jest/pull/9291))
- `[jest-config]` [**BREAKING**] Support `.mjs` config files ([#9431](https://github.com/facebook/jest/pull/9431))
- `[jest-core]` Support reporters as default exports ([#9161](https://github.com/facebook/jest/pull/9161))
- `[jest-core]` Support `--findRelatedTests` paths case insensitivity on Windows ([#8900](https://github.com/facebook/jest/issues/8900))
- `[jest-diff]` Add options for colors and symbols ([#8841](https://github.com/facebook/jest/pull/8841))
Expand Down
16 changes: 16 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,22 @@ module.exports = {
presets: ['@babel/preset-typescript'],
test: /\.tsx?$/,
},
// we want this file to keep `import()`, so exclude the transform for it
{
plugins: ['@babel/plugin-syntax-dynamic-import'],
presets: [
'@babel/preset-typescript',
[
'@babel/preset-env',
{
exclude: ['@babel/plugin-proposal-dynamic-import'],
shippedProposals: true,
targets: {node: 8},
},
],
],
test: 'packages/jest-config/src/readConfigFileAndSetRootDir.ts',
},
],
plugins: [
['@babel/plugin-transform-modules-commonjs', {allowTopLevelThis: true}],
Expand Down
21 changes: 0 additions & 21 deletions e2e/__tests__/cjsConfigFile.test.ts

This file was deleted.

38 changes: 38 additions & 0 deletions e2e/__tests__/esmConfigFile.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {onNodeVersions} from '@jest/test-utils';
import {json as runWithJson} from '../runJest';

test('reads config from cjs file', () => {
const {json, exitCode} = runWithJson('esm-config/cjs', ['--show-config'], {
skipPkgJsonCheck: true,
});

expect(exitCode).toBe(0);
expect(json.configs).toHaveLength(1);
expect(json.configs[0].displayName).toEqual({
color: 'white',
name: 'Config from cjs file',
});
});

// not unflagged for other versions yet. Update this range if that changes
onNodeVersions('^13.2.0', () => {
test('reads config from mjs file', () => {
const {json, exitCode} = runWithJson('esm-config/mjs', ['--show-config'], {
skipPkgJsonCheck: true,
});

expect(exitCode).toBe(0);
expect(json.configs).toHaveLength(1);
expect(json.configs[0].displayName).toEqual({
color: 'white',
name: 'Config from mjs file',
});
});
});
File renamed without changes.
File renamed without changes.
File renamed without changes.
10 changes: 10 additions & 0 deletions e2e/esm-config/mjs/__tests__/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

test('dummy test', () => {
expect(1).toBe(1);
});
11 changes: 11 additions & 0 deletions e2e/esm-config/mjs/jest.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

export default {
displayName: 'Config from mjs file',
testEnvironment: 'node',
};
3 changes: 3 additions & 0 deletions e2e/esm-config/mjs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"jest": {}
}
201 changes: 201 additions & 0 deletions packages/jest-cli/src/init/__tests__/__snapshots__/init.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,207 @@ Object {
}
`;

exports[`init has-jest-config-file-mjs ask the user whether to override config or not user answered with "Yes" 1`] = `
Object {
"initial": true,
"message": "It seems that you already have a jest configuration, do you want to override it?",
"name": "continue",
"type": "confirm",
}
`;

exports[`init project with package.json and no jest config all questions answered with answer: "No" should generate empty config with mjs extension 1`] = `
"// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html

export default {
SimenB marked this conversation as resolved.
Show resolved Hide resolved
// All imported modules in your tests should be mocked automatically
// automock: false,

// Stop running tests after \`n\` failures
// bail: 0,

// Respect \\"browser\\" field in package.json when resolving modules
// browser: false,

// The directory where Jest should store its cached dependency information
// cacheDirectory: \\"/tmp/jest\\",

// Automatically clear mock calls and instances between every test
// clearMocks: false,

// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,

// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,

// The directory where Jest should output its coverage files
// coverageDirectory: undefined,

// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// \\"/node_modules/\\"
// ],

// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// \\"json\\",
// \\"text\\",
// \\"lcov\\",
// \\"clover\\"
// ],

// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,

// A path to a custom dependency extractor
// dependencyExtractor: undefined,

// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,

// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],

// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,

// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,

// A set of global variables that need to be available in all test environments
// globals: {},

// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: \\"50%\\",

// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// \\"node_modules\\"
// ],

// An array of file extensions your modules use
// moduleFileExtensions: [
// \\"js\\",
// \\"json\\",
// \\"jsx\\",
// \\"ts\\",
// \\"tsx\\",
// \\"node\\"
// ],

// A map from regular expressions to module names that allow to stub out resources with a single module
// moduleNameMapper: {},

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

// Activates notifications for test results
// notify: false,

// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: \\"failure-change\\",

// A preset that is used as a base for Jest's configuration
// preset: undefined,

// Run tests from one or more projects
// projects: undefined,

// Use this configuration option to add custom reporters to Jest
// reporters: undefined,

// Automatically reset mock state between every test
// resetMocks: false,

// Reset the module registry before running each individual test
// resetModules: false,

// A path to a custom resolver
// resolver: undefined,

// Automatically restore mock state between every test
// restoreMocks: false,

// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,

// A list of paths to directories that Jest should use to search for files in
// roots: [
// \\"<rootDir>\\"
// ],

// Allows you to use a custom runner instead of Jest's default test runner
// runner: \\"jest-runner\\",

// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],

// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],

// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],

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

// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},

// Adds a location field to test results
// testLocationInResults: false,

// The glob patterns Jest uses to detect test files
// testMatch: [
// \\"**/__tests__/**/*.[jt]s?(x)\\",
// \\"**/?(*.)+(spec|test).[tj]s?(x)\\"
// ],

// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// \\"/node_modules/\\"
// ],

// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],

// This option allows the use of a custom results processor
// testResultsProcessor: undefined,

// This option allows use of a custom test runner
// testRunner: \\"jasmine2\\",

// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: \\"http://localhost\\",

// Setting this value to \\"fake\\" allows the use of fake timers for functions such as \\"setTimeout\\"
// timers: \\"real\\",

// A map from regular expressions to paths to transformers
// transform: undefined,

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// \\"/node_modules/\\"
// ],

// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,

// Indicates whether each individual test should be reported during the run
// verbose: undefined,

// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],

// Whether to use watchman for file crawling
// watchman: true,
};
"
`;

exports[`init project with package.json and no jest config all questions answered with answer: "No" should return the default configuration (an empty config) 1`] = `
"// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

export default {};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "type_module",
"scripts": {
"test": "different-test-runner"
},
"type": "module"
}
19 changes: 18 additions & 1 deletion packages/jest-cli/src/init/__tests__/init.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@
import * as fs from 'fs';
import * as path from 'path';
import prompts from 'prompts';
import {constants} from 'jest-config';
import init from '../';
import {JEST_CONFIG_EXT_ORDER} from '../constants';
import {onNodeVersions} from '@jest/test-utils';

const {JEST_CONFIG_EXT_ORDER} = constants;

jest.mock('prompts');
jest.mock('../../../../jest-config/build/getCacheDirectory', () => () =>
Expand Down Expand Up @@ -52,6 +55,20 @@ describe('init', () => {

expect(evaluatedConfig).toEqual({});
});

onNodeVersions('^13.1.0', () => {
it('should generate empty config with mjs extension', async () => {
prompts.mockReturnValueOnce({});

await init(resolveFromFixture('type_module'));

expect(fs.writeFileSync.mock.calls[0][0].endsWith('.mjs')).toBe(true);

const writtenJestConfig = fs.writeFileSync.mock.calls[0][1];

expect(writtenJestConfig).toMatchSnapshot();
});
});
});

describe('some questions answered with answer: "Yes"', () => {
Expand Down
17 changes: 0 additions & 17 deletions packages/jest-cli/src/init/constants.ts

This file was deleted.

Loading