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

add init option #6442

Merged
merged 8 commits into from
Jun 20, 2018
Merged

add init option #6442

merged 8 commits into from
Jun 20, 2018

Conversation

ranyitz
Copy link
Contributor

@ranyitz ranyitz commented Jun 12, 2018

Summary

Following the feature request in #6403 this PR adds jest --init option.

When a user type jest --init in a project directory, he will be prompted with questions that will help jest to create a basic configuration, suitable for the project. It will create a jest.config.js file and modify package.json if needed.

jest-init

What's inside?

  • prompts package added.
  • jest-config
    • descriptions module created - reusable short explanations for configuration options.
    • cacheDirectory, the dynamic bit of the defaults module, now has it's own module so it'll be easier to mock.
  • jest-cli
    • the --init options triggers the init process.

Thoughts

  • Right now we're generating the config using all of the options, maybe we can omit options like cacheDirectory which are less likely to be changed by the user.
  • I could not write a proper e2e because I'm not sure how to fake the user answers to the prompt without mocking.

How does the generated/modified files looks like?

jest.config.js

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

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

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

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

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

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

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

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

  // 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: [],

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

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

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

package.json

{
  "name": "test-jest-init",
  "version": "1.0.0",
  "main": "jest.config.js",
  "dependencies": {
    "typescript": "^2.9.1"
  },
  "scripts": {
    "test": "jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

Test plan

Verify that each file system condition (e.g. has jest config, has typescript dependency) affects the prompts, and that each response to the prompts changes the way files will e generated.

saved 1 snapshot of the whole generated file with comments, and evaluate each permutation to verify the returned value from the config.

@ranyitz
Copy link
Contributor Author

ranyitz commented Jun 12, 2018

prompts currently not support node 6, filed an issue


const overrideKeys: Array<string> = Object.keys(overrides);

const stringifyOption = (
Copy link
Member

Choose a reason for hiding this comment

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

does this have to exist inside the generateConfigFile closure?

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'll move it out of there 😉


const overrides: Object = {};

if (typescript) {
Copy link
Member

Choose a reason for hiding this comment

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

I'm not sure if we should add ts-jest - it forces people to install another dependency and babel 7 supports typescript..

@rickhanlonii @thymikee @orta thoughts?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Also to the problem with ts-jest is that it may happen that older version will be installed, e.g. right after new Jest major release. Maybe we can add another prompt?

Copy link
Member

Choose a reason for hiding this comment

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

I feel like this isn't that much of a problem, I've yet to have ts-jest break between jest versions (but I don't see every issue on this repo) and it's triggered on a prompt that checks your dependencies for typescript itself, so using babel's transformer won't necessarily make sense for that kind of setup by default.

@SimenB
Copy link
Member

SimenB commented Jun 16, 2018

I'm really excited by this, thanks for working on it!

Code wise I think it looks good, but it would be awesome to have some docs on it (plus a changelog entry 🙂)

I'm honestly fine with this just supporting node 8 and up (as it's just something that would be run on a developer's machine), but we'd still need prompts to at least drop the engine requirement and implement a more manual "cannot be run on older than node 8" thing.

Copy link
Collaborator

@thymikee thymikee left a comment

Choose a reason for hiding this comment

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

Wouldn't it make sense to create a new package out of it, like jest-init or jest-cli-init? jest-cli is already quite bloated

@ranyitz
Copy link
Contributor Author

ranyitz commented Jun 16, 2018

@SimenB @thymikee Thanks for the review.

I've added docs and a changelog entry. I've also realized that it makes sense to put jest --init in the getting started guide, but only after the original "getting started" which instruct the user to add

{
  "scripts": {
    "test": "jest"
  }
}

So i've added support for this case, and now we'll not ask the user that add it if it's already there.


I agree that we need to decide about how we initialize jest for a typescript project, and that what we currently have is only OKish and has some problems.

Regarding prompts, opened another issue with the update asking to remove the engines field.

@ranyitz
Copy link
Contributor Author

ranyitz commented Jun 19, 2018

Update, prompts now supports node 6.

yarn.lock Outdated
@@ -7546,6 +7550,13 @@ promise@^7.1.1:
dependencies:
asap "~2.0.3"

prompts@^0.1.8:
Copy link
Member

Choose a reason for hiding this comment

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

mind running yarn so this is updated?

@codecov-io
Copy link

codecov-io commented Jun 19, 2018

Codecov Report

Merging #6442 into master will increase coverage by 0.29%.
The diff coverage is 89.58%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #6442      +/-   ##
==========================================
+ Coverage   63.48%   63.78%   +0.29%     
==========================================
  Files         227      234       +7     
  Lines        8697     8791      +94     
  Branches        3        4       +1     
==========================================
+ Hits         5521     5607      +86     
- Misses       3175     3183       +8     
  Partials        1        1
Impacted Files Coverage Δ
packages/jest-config/src/defaults.js 100% <ø> (+7.14%) ⬆️
packages/jest-config/src/index.js 37.03% <ø> (+5.66%) ⬆️
...ages/jest-cli/src/lib/init/generate_config_file.js 100% <100%> (ø)
packages/jest-cli/src/lib/init/questions.js 100% <100%> (ø)
...kages/jest-cli/src/lib/init/modify_package_json.js 100% <100%> (ø)
packages/jest-config/src/descriptions.js 100% <100%> (ø)
packages/jest-cli/src/constants.js 100% <100%> (ø) ⬆️
packages/jest-cli/src/lib/init/errors.js 50% <50%> (ø)
packages/jest-config/src/get_cache_directory.js 90% <87.5%> (ø)
packages/jest-cli/src/lib/init/index.js 88.88% <88.88%> (ø)
... and 9 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 7542f24...92a68b8. Read the comment docs.

Copy link
Member

@SimenB SimenB left a comment

Choose a reason for hiding this comment

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

Awesome, thanks!

@rickhanlonii
Copy link
Member

Agree with @thymikee, we should move this to jest-init

@cpojer cpojer merged commit d9b324e into jestjs:master Jun 20, 2018
@ranyitz ranyitz deleted the jest-init branch June 20, 2018 19:34
@SimenB
Copy link
Member

SimenB commented Jun 22, 2018

@ranyitz mind mocking out console.log in the tests? Quite noisy when I run them.

Asserting on the output might make sense, but if not, just stub it out 🙂

@ranyitz
Copy link
Contributor Author

ranyitz commented Jun 22, 2018

@SimenB I agree, I'll do it later on today.

calebeby referenced this pull request in Pigmice2733/scouting-frontend Jun 30, 2018
This Pull Request updates dependency [jest](https://github.com/facebook/jest) from `v23.1.0` to `v23.2.0`



<details>
<summary>Release Notes</summary>

### [`v23.2.0`](https://github.com/facebook/jest/blob/master/CHANGELOG.md#&#8203;2320)
[Compare Source](jestjs/jest@v23.1.0...v23.2.0)
##### Features

- `[jest-each]` Add support for keyPaths in test titles ([#&#8203;6457](`https://github.com/facebook/jest/pull/6457`))
- `[jest-cli]` Add `jest --init` option that generates a basic configuration file with a short description for each option ([#&#8203;6442](`https://github.com/facebook/jest/pull/6442`))
- `[jest.retryTimes]` Add `jest.retryTimes()` option that allows failed tests to be retried n-times when using jest-circus. ([#&#8203;6498](`https://github.com/facebook/jest/pull/6498`))
##### Fixes

- `[jest-cli]` Add check to make sure one or more tests have run before notifying when using `--notify` ([#&#8203;6495](`https://github.com/facebook/jest/pull/6495`))
- `[jest-cli]` Pass `globalConfig` as a parameter to `globalSetup` and `globalTeardown` functions ([#&#8203;6486](`https://github.com/facebook/jest/pull/6486`))
- `[jest-config]` Add missing options to the `defaults` object ([#&#8203;6428](`https://github.com/facebook/jest/pull/6428`))
- `[expect]` Using symbolic property names in arrays no longer causes the `toEqual` matcher to fail ([#&#8203;6391](`https://github.com/facebook/jest/pull/6391`))
- `[expect]` `toEqual` no longer tries to compare non-enumerable symbolic properties, to be consistent with non-symbolic properties. ([#&#8203;6398](`https://github.com/facebook/jest/pull/6398`))
- `[jest-util]` `console.timeEnd` now properly log elapsed time in milliseconds. ([#&#8203;6456](`https://github.com/facebook/jest/pull/6456`))
- `[jest-mock]` Fix `MockNativeMethods` access in react-native `jest.mock()` ([#&#8203;6505](`https://github.com/facebook/jest/pull/6505`))
##### Chore & Maintenance

- `[docs]` Add jest-each docs for 1 dimensional arrays ([#&#8203;6444](`https://github.com/facebook/jest/pull/6444`/files))

---

</details>




---

This PR has been generated by [Renovate Bot](https://renovatebot.com).
newmanicspree added a commit to newmanicspree/typescript-book that referenced this pull request Oct 30, 2019
Included `testMatch` and edited `transform` entries to meet [#6442](jestjs/jest#6442) from the Jest community.
newmanicspree added a commit to newmanicspree/typescript-book that referenced this pull request Oct 30, 2019
Included `testMatch` and edited `transform` entries to meet [#6442](jestjs/jest#6442) from the Jest community.
@github-actions
Copy link

This pull request 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

Successfully merging this pull request may close these issues.

8 participants