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

jest --init to set up package.json with default values #6403

Closed
fluffynuts opened this issue Jun 6, 2018 · 22 comments
Closed

jest --init to set up package.json with default values #6403

fluffynuts opened this issue Jun 6, 2018 · 22 comments

Comments

@fluffynuts
Copy link

🚀 Feature Proposal

Much like other tools (tsc, tslint, etc), it would be very useful if there were an --init option for jest cli to supplement the existing package.json with all possible settings for jest, with their default values.

Motivation

This would make custom configuration easier: instead of having to refer to documentation every time, one could simply jest --init and look for the setting which describes what it does to edit that.

Example

# jest --init

Pitch

Because jest is the master of the configuration which is available -- it makes sense that jest should be able to populate these settings. Ideally, this --init would also guide the user through some more common options, such as:

  1. "Is this a TypeScript project?" (positive answer enables the ts-jest transform, alters "testMatch" to "**/.spec.ts", adds "ts" to "moduleFileExtensions", adds "/.\.d\.td/" to "watchIgnorePatterns", etc
  2. "Do you want coverage reports?" (positive answer sets "coverageDirectory" to "coverage" (ignored by default with github .gitignore for node projects)
  3. "Would you like Jest to use Jest for 'npm test'?" (positive answer sets "test" npm script to "jest")

Jest already provides probably the best test running framework I've used (between jasmine, mocha and jest), with so many things already baked in (coverage! What a win!) -- it just seems like one of the aims of the project is to be as polished as possible. A guided --init would, imo, help a lot.

@thymikee
Copy link
Collaborator

thymikee commented Jun 6, 2018

Awesome idea!

@SimenB
Copy link
Member

SimenB commented Jun 6, 2018

Yeah, I like it! Something about testEnvironment, and mock clearing would be great as well

@rickhanlonii
Copy link
Member

Love this, something like it came up during the Jest Summit Q&A

@SimenB
Copy link
Member

SimenB commented Jun 6, 2018

PR most welcome! 🙂

@ranyitz
Copy link
Contributor

ranyitz commented Jun 6, 2018

That's a great idea, it will make jest even easier to start with. 🙂

I'd love to work on this.

While creating the config, should we go with jest.config.js or jest key in package.json?

@SimenB
Copy link
Member

SimenB commented Jun 6, 2018

Advantage of jest.config.js is comments. It's yet another file, though.

It can be a choice in the prompt, though?

@ranyitz
Copy link
Contributor

ranyitz commented Jun 6, 2018

@SimenB If we'll go with @fluffynuts idea to add all options,

with all possible settings for jest, with their default values.

we'll end up with around 80 lines of configuration. I wouldn't add this amount to the user's package.json, in this case i would probably prefer jest.config.js

@SimenB
Copy link
Member

SimenB commented Jun 7, 2018

I don't think we should add defaults, only overrides

@fluffynuts
Copy link
Author

If the config is generated as .js, then perhaps include all the defaults commented out? This has really helped in discovery of tsconfig and tslint configuration -- instead of having to hit up the docs sites every time, I can just trawl through the generated config.

@SimenB
Copy link
Member

SimenB commented Jun 7, 2018

That sounds like a good idea!

@ranyitz
Copy link
Contributor

ranyitz commented Jun 7, 2018

@SimenB @fluffynuts Ok, we've got some decisions to make, and I would appreciate your opinion:

  1. Which questions should we ask?

That's what I currently have:

jest--init

  1. How should the config file look like?
  • Should we add all the defaults including things like cacheDirectory?
// For a detailed explanation regarding each configuration property, please visit:
// https://facebook.github.io/jest/docs/en/configuration.html

module.exports = {
  // automock: false,
  // bail: false,
  // browser: false,
  // cache: true,
  // cacheDirectory: "/var/folders/tz/39sb86z96tj_2cqqkm1kfkh9bwd75d/T/jest_ocrnot",
  // changedFilesWithAncestor: false,
  clearMocks: true,
  // coveragePathIgnorePatterns: [
  //   "/node_modules/"
  // ],
  // coverageReporters: [
  //   "json",
  //   "text",
  //   "lcov",
  //   "clover"
  // ],
  // detectLeaks: false,
  // detectOpenHandles: false,
  // errorOnDeprecated: false,
  // expand: false,
  // filter: null,
  // forceCoverageMatch: [],
  // globalSetup: null,
  // globalTeardown: null,
  globals: {
    "ts-jest": {
      "tsConfigFile": "tsconfig.json"
    }
  },
  // haste: {
  //   "providesModuleNodeModules": []
  // },
  // moduleDirectories: [
  //   "node_modules"
  // ],
  moduleFileExtensions: [
    "ts",
    "tsx",
    "js"
  ],
  // moduleNameMapper: {},
  // modulePathIgnorePatterns: [],
  // noStackTrace: false,
  // notify: false,
  // notifyMode: "always",
  // preset: null,
  // resetMocks: false,
  // resetModules: false,
  // restoreMocks: false,
  // runTestsByPath: false,
  // runner: "jest-runner",
  // skipFilter: false,
  // snapshotSerializers: [],
  testEnvironment: "node",
  // testEnvironmentOptions: {},
  // testFailureExitCode: 1,
  // testLocationInResults: false,
  testMatch: [
    "**/__tests__/*.+(ts|tsx|js)"
  ],
  // testPathIgnorePatterns: [
  //   "/node_modules/"
  // ],
  // testRegex: "",
  // testResultsProcessor: null,
  // testURL: "about:blank",
  // timers: "real",
  // transformIgnorePatterns: [
  //   "/node_modules/"
  // ],
  // useStderr: false,
  // verbose: null,
  // watch: false,
  // watchPathIgnorePatterns: [],
  // watchman: true,
};
  1. While choosing typescript option, should we suggest to install ts-jest/add it to the devDependencies?

  2. If the user already had a jest configuration in package.json/jest.config.js should we prompt whether to override the current one or abort?

Let me know what you think!

@rickhanlonii
Copy link
Member

This is great!!

  1. That's a good start, I'm cool with starting with that and iterating

  2. We could model off of the way vscode does it (and yeah I think all settings make sense?):

module.exports = {
  // Comment explanation
  // setting: 'default-value',

  // Another explanation
  // setting2: 'default-value',
};
  1. I'd remove the typescript question and we can figure out a way to detect possible environments and prompt based on those?

  2. Yeah that's cool

@fluffynuts
Copy link
Author

Considering the popularity of TypeScript and that there is a module to ease testing TypeScript, I would advocate for including the question and configuring the helper, simply because someone not aware of the helper will likely waste time setting up a watched build process (I very nearly did exactly this) to get to continual testing. I don't think it would be super difficult and I do think that the benefit to the user would be valuable. I realize that there are other environments which might be catered for - perhaps the inclusion of one popular one would spark conversation around supporting the others?

@ranyitz
Copy link
Contributor

ranyitz commented Jun 8, 2018

@rickhanlonii I like the way vscode models the config. About the explanations, it means that we'll have to maintain an object with a short explanation for each configuration option, should it be in jest-config? (so extensions like vscode-jest could use it to give nice tooltips with the explanations)

About Typescript, we can look for typescript dependency in package.json and prompt accordingly:

Would you like to setup jest for typescript?

What do you think?

@rickhanlonii
Copy link
Member

Yeah I agree @fluffynuts -- just to be clear, I'm not saying that we don't offer a ts CLI setup option, I'm saying we try to make it smarter than just asking every user "are you using typescript"

@ranyitz both of those are great ideas I think. I'd probably have the TS message be something like "Typescript detected, you do want to setup jest for typescript"? Some kind of language that shows we did some auto detection

@ranyitz
Copy link
Contributor

ranyitz commented Jun 10, 2018

Typescript detection added:

jest--init-improved

I've added a short explanation for each option and changed the looks of the generated file:

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

module.exports = {
  // All imported modules in your tests should be mocked automatically
  // automock: false,

  // Stop running tests after the first failure
  // bail: false,

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

  // The directory where Jest should store its cached dependency information
  // cacheDirectory: "/var/folders/tz/39sb86z96tj_2cqqkm1kfkh9bwd75d/T/jest_ocrnot",

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

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

  // 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: "coverage",

  // 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,

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

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

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

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

  // A set of global variables that need to be available in all test environments
  globals: {
    "ts-jest": {
      "tsConfigFile": "tsconfig.json"
    }
  },

  // 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: [
    "ts",
    "tsx",
    "js"
  ],

  // 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: "always",

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

  // 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: undefined,

  // 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: undefined,

  // The path to a module that runs some code to configure or set up the testing framework before each test
  // setupTestFrameworkScriptFile: undefined,

  // 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: "node",

  // 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__/*.+(ts|tsx|js)"
  ],

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

  // The regexp pattern Jest uses to detect test files
  // testRegex: "",

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

  // This option allows use of a custom test runner
  // testRunner: undefined,

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

  // 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: {
    "^.+\\.(ts|tsx)$": "ts-jest"
  },

  // 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: null,

  // 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,
};

All undefined values should be corrected after #6428 will be merged.

@rickhanlonii Is that something we can start with?

@SimenB
Copy link
Member

SimenB commented Jun 10, 2018

I think that's an awesome starting point. Great job!

@rickhanlonii
Copy link
Member

Beauty, ship it!

One small request would be to have node as the first option instead of JSDOM, since we'll be switching to node by default sometime soon

@ranyitz
Copy link
Contributor

ranyitz commented Jun 12, 2018

Thanks @SimenB @rickhanlonii 😊
Switched to node by default.

I've opened a PR #6442 but it's failing, the package that i've used for prompting does not support node 6.

I'll see if they are willing to transpile their code

@suhashankare
Copy link

Awesome! Guys, was expecting such features, keep updating 👍

@SimenB
Copy link
Member

SimenB commented Jul 3, 2018

This is done #6442

@SimenB SimenB closed this as completed Jul 3, 2018
@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 12, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

6 participants