Monday 8 April 2019

Node + TypeScript + Rollup + Jest

To install Jest:

$ npm install jest --save-dev


Jest CLI


$ npx jest --help
Usage: jest [--config=<pathToConfigFile>] [TestPathPattern]

Options:
  --help, -h                    Show help                              [boolean]
  --version, -v                 Print the version and exit             [boolean]
  --all                         The opposite of `onlyChanged`. If `onlyChanged`
                                is set by default, running jest with `--all`
                                will force Jest to run all tests instead of
                                running only tests related to changed files.
  --automock                    Automock all files by default.         [boolean]
  --bail, -b                    Exit the test suite immediately after `n` number
                                of failing tests.
  --browser                     Respect the "browser" field in package.json when
                                resolving modules. Some packages export
                                different versions based on whether they are
                                operating in node.js or a browser.     [boolean]
  --cache                       Whether to use the transform cache. Disable the
                                cache using --no-cache.                [boolean]
  --cacheDirectory              The directory where Jest should store its cached
                                dependency information.                 [string]
  --changedFilesWithAncestor    Runs tests related to the current changes and
                                the changes made in the last commit. Behaves
                                similarly to `--onlyChanged`.          [boolean]
  --changedSince                Runs tests related to the changes since the
                                provided branch. If the current branch has
                                diverged from the given branch, then only
                                changes made locally will be tested. Behaves
                                similarly to `--onlyChanged`.           [string]
  --ci                          Whether to run Jest in continuous integration
                                (CI) mode. This option is on by default in most
                                popular CI environments. It will  prevent
                                snapshots from being written unless explicitly
                                requested.            [boolean] [default: false]
  --clearCache                  Clears the configured Jest cache directory and
                                then exits. Default directory can be found by
                                calling jest --showConfig              [boolean]
  --clearMocks                  Automatically clear mock calls and instances
                                between every test. Equivalent to calling
                                jest.clearAllMocks() between each test.[boolean]
  --collectCoverage             Alias for --coverage.                  [boolean]
  --collectCoverageFrom         A glob pattern relative to <rootDir> matching
                                the files that coverage info needs to be
                                collected from.                         [string]
  --collectCoverageOnlyFrom     Explicit list of paths coverage will be
                                restricted to.                           [array]
  --color                       Forces test results output color highlighting
                                (even if stdout is not a TTY). Set to false if
                                you would like to have no colors.      [boolean]
  --colors                      Alias for `--color`.                   [boolean]
  --config, -c                  The path to a jest config file specifying how to
                                find and execute tests. If no rootDir is set in
                                the config, the directory containing the config
                                file is assumed to be the rootDir for the
                                project.This can also be a JSON encoded value
                                which Jest will use as configuration.   [string]
  --coverage                    Indicates that test coverage information should
                                be collected and reported in the output.
                                                                       [boolean]
  --coverageDirectory           The directory where Jest should output its
                                coverage files.                         [string]
  --coveragePathIgnorePatterns  An array of regexp pattern strings that are
                                matched against all file paths before executing
                                the test. If the file pathmatches any of the
                                patterns, coverage information will be skipped.
                                                                         [array]
  --coverageReporters           A list of reporter names that Jest uses when
                                writing coverage reports. Any istanbul reporter
                                can be used.                             [array]
  --coverageThreshold           A JSON string with which will be used to
                                configure minimum threshold enforcement for
                                coverage results                        [string]
  --debug                       Print debugging info about your jest config.
                                                                       [boolean]
  --detectLeaks                 **EXPERIMENTAL**: Detect memory leaks in tests.
                                After executing a test, it will try to garbage
                                collect the global object used, and fail if it
                                was leaked            [boolean] [default: false]
  --detectOpenHandles           Print out remaining open handles preventing Jest
                                from exiting at the end of a test run. Implies
                                `runInBand`.          [boolean] [default: false]
  --env                         The test environment used for all tests. This
                                can point to any file or node module. Examples:
                                `jsdom`, `node` or `path/to/my-environment.js`
                                                                        [string]
  --errorOnDeprecated           Make calling deprecated APIs throw helpful error
                                messages.             [boolean] [default: false]
  --expand, -e                  Use this flag to show full diffs instead of a
                                patch.                                 [boolean]
  --filter                      Path to a module exporting a filtering function.
                                This method receives a list of tests which can
                                be manipulated to exclude tests from running.
                                Especially useful when used in conjunction with
                                a testing infrastructure to filter known broken
                                tests.                                  [string]
  --findRelatedTests            Find related tests for a list of source files
                                that were passed in as arguments. Useful for
                                pre-commit hook integration to run the minimal
                                amount of tests necessary.             [boolean]
  --forceExit                   Force Jest to exit after all tests have
                                completed running. This is useful when resources
                                set up by test code cannot be adequately cleaned
                                up.                                    [boolean]
  --globalSetup                 The path to a module that runs before All Tests.
                                                                        [string]
  --globalTeardown              The path to a module that runs after All Tests.
                                                                        [string]
  --globals                     A JSON string with map of global variables that
                                need to be available in all test environments.
                                                                        [string]
  --haste                       A JSON string with map of variables for the
                                haste module system                     [string]
  --init                        Generate a basic configuration file    [boolean]
  --json                        Prints the test results in JSON. This mode will
                                send all other test output and user messages to
                                stderr.                                [boolean]
  --lastCommit                  Run all tests affected by file changes in the
                                last commit made. Behaves similarly to
                                `--onlyChanged`.                       [boolean]
  --listTests                   Lists all tests Jest will run given the
                                arguments and exits. Most useful in a CI system
                                together with `--findRelatedTests` to determine
                                the tests Jest will run based on specific files
                                                      [boolean] [default: false]
  --logHeapUsage                Logs the heap usage after every test. Useful to
                                debug memory leaks. Use together with
                                `--runInBand` and `--expose-gc` in node.
                                                                       [boolean]
  --mapCoverage                 Maps code coverage reports against original
                                source code when transformers supply source
                                maps.

                                DEPRECATED                             [boolean]
  --maxConcurrency              Specifies the maximum number of tests that are
                                allowed to runconcurrently. This only affects
                                tests using `test.concurrent`.
                                                           [number] [default: 5]
  --maxWorkers, -w              Specifies the maximum number of workers the
                                worker-pool will spawn for running tests. This
                                defaults to the number of the cores available on
                                your machine. (its usually best not to override
                                this default)                           [number]
  --moduleDirectories           An array of directory names to be searched
                                recursively up from the requiring module's
                                location.                                [array]
  --moduleFileExtensions        An array of file extensions your modules use.
                                If you require modules without specifying a
                                file extension, these are the extensions Jest
                                will look for.                           [array]
  --moduleNameMapper            A JSON string with a map from regular
                                expressions to module names that allow to stub
                                out resources, like images or styles with a
                                single module                           [string]
  --modulePathIgnorePatterns    An array of regexp pattern strings that are
                                matched against all module paths before those
                                paths are to be considered "visible" to the
                                module loader.                           [array]
  --modulePaths                 An alternative API to setting the NODE_PATH env
                                variable, modulePaths is an array of absolute
                                paths to additional locations to search when
                                resolving modules.                       [array]
  --noStackTrace                Disables stack trace in test results output
                                                                       [boolean]
  --notify                      Activates notifications for test results.
                                                                       [boolean]
  --notifyMode                  Specifies when notifications will appear for
                                test results.
                                            [string] [default: "failure-change"]
  --onlyChanged, -o             Attempts to identify which tests to run based on
                                which files have changed in the current
                                repository. Only works if you're running tests
                                in a git or hg repository at the moment.
                                                                       [boolean]
  --onlyFailures, -f            Run tests that failed in the previous execution.
                                                                       [boolean]
  --outputFile                  Write test results to a file when the --json
                                option is also specified.               [string]
  --passWithNoTests             Will not fail if no tests are found (for example
                                while using `--testPathPattern`.)
                                                      [boolean] [default: false]
  --preset                      A preset that is used as a base for Jest's
                                configuration.                          [string]
  --prettierPath                The path to the "prettier" module used for
                                inline snapshots.                       [string]
  --projects                    A list of projects that use Jest to run all
                                tests of all projects in a single instance of
                                Jest.                                    [array]
  --reporters                   A list of custom reporters for the test suite.
                                                                         [array]
  --resetMocks                  Automatically reset mock state between every
                                test. Equivalent to calling jest.resetAllMocks()
                                between each test.                     [boolean]
  --resetModules                If enabled, the module registry for every test
                                file will be reset before running each
                                individual test.                       [boolean]
  --resolver                    A JSON string which allows the use of a custom
                                resolver.                               [string]
  --restoreMocks                Automatically restore mock state and
                                implementation between every test. Equivalent to
                                calling jest.restoreAllMocks() between each
                                test.                                  [boolean]
  --rootDir                     The root directory that Jest should scan for
                                tests and modules within.               [string]
  --roots                       A list of paths to directories that Jest should
                                use to search for files in.              [array]
  --runInBand, -i               Run all tests serially in the current process
                                (rather than creating a worker pool of child
                                processes that run tests). This is sometimes
                                useful for debugging, but such use cases are
                                pretty rare.                           [boolean]
  --runTestsByPath              Used when provided patterns are exact file
                                paths. This avoids converting them into a
                                regular expression and matching it against every
                                single file.          [boolean] [default: false]
  --runner                      Allows to use a custom runner instead of Jest's
                                default test runner.                    [string]
  --setupFiles                  A list of paths to modules that run some code
                                to configure or set up the testing environment
                                before each test.                        [array]
  --setupFilesAfterEnv          A list of paths to modules that run some code
                                to configure or set up the testing framework
                                before each test                         [array]
  --showConfig                  Print your jest config and then exits. [boolean]
  --silent                      Prevent tests from printing messages through the
                                console.                               [boolean]
  --skipFilter                  Disables the filter provided by --filter. Useful
                                for CI jobs, or local enforcement when fixing
                                tests.                                 [boolean]
  --snapshotSerializers         A list of paths to snapshot serializer modules
                                Jest should use for snapshot testing.    [array]
  --testEnvironment             Alias for --env                         [string]
  --testEnvironmentOptions      Test environment options that will be passed to
                                the testEnvironment. The relevant options depend
                                on the environment.                     [string]
  --testFailureExitCode         Exit code of `jest` command if the test run
                                failed                                  [string]
  --testLocationInResults       Add `location` information to the test results
                                                      [boolean] [default: false]
  --testMatch                   The glob patterns Jest uses to detect test
                                files.                                   [array]
  --testNamePattern, -t         Run only tests with a name that matches the
                                regex pattern.                          [string]
  --testPathIgnorePatterns      An array of regexp pattern strings that are
                                matched against all test paths before executing
                                the test. If the test path matches any of the
                                patterns, it will be skipped.            [array]
  --testPathPattern             A regexp pattern string that is matched against
                                all tests paths before executing the test.
                                                                         [array]
  --testRegex                   A string or array of string regexp patterns that
                                Jest uses to detect test files.          [array]
  --testResultsProcessor        Allows the use of a custom results processor.
                                This processor must be a node module that
                                exports a function expecting as the first
                                argument the result object.             [string]
  --testRunner                  Allows to specify a custom test runner. The
                                default is  `jasmine2`. A path to a custom test
                                runner can be provided:
                                `<rootDir>/path/to/testRunner.js`.      [string]
  --testSequencer               Allows to specify a custom test sequencer. The
                                default is `@jest/test-sequencer`. A path to a
                                custom test sequencer can be provided:
                                `<rootDir>/path/to/testSequencer.js`    [string]
  --testURL                     This option sets the URL for the jsdom
                                environment.                            [string]
  --timers                      Setting this value to fake allows the use of
                                fake timers for functions such as setTimeout.
                                                                        [string]
  --transform                   A JSON string which maps from regular
                                expressions to paths to transformers.   [string]
  --transformIgnorePatterns     An array of regexp pattern strings that are
                                matched against all source file paths before
                                transformation.                          [array]
  --unmockedModulePathPatterns  An array of regexp pattern strings that are
                                matched against all modules before the module
                                loader will automatically return a mock for
                                them.                                    [array]
  --updateSnapshot, -u          Use this flag to re-record snapshots. Can be
                                used together with a test suite pattern or with
                                `--testNamePattern` to re-record snapshot for
                                test matching the pattern              [boolean]
  --useStderr                   Divert all output to stderr.           [boolean]
  --verbose                     Display individual test results with the test
                                suite hierarchy.                       [boolean]
  --watch                       Watch files for changes and rerun tests related
                                to changed files. If you want to re-run all
                                tests when a file has changed, use the
                                `--watchAll` option.                   [boolean]
  --watchAll                    Watch files for changes and rerun all tests. If
                                you want to re-run only the tests related to the
                                changed files, use the `--watch` option.
                                                                       [boolean]
  --watchPathIgnorePatterns     An array of regexp pattern strings that are
                                matched against all paths before trigger test
                                re-run in watch mode. If the test path matches
                                any of the patterns, it will be skipped. [array]
  --watchman                    Whether to use watchman for file crawling.
                                Disable using --no-watchman.           [boolean]

Documentation: https://jestjs.io/

---



To create a basic config file:

$ npx jest --init

This will crate config file after prompting you couple of questions:

$  npx jest --init

The following questions will help Jest to create a suitable configuration for your project

✔ Would you like to use Jest when running "test" script in "package.json"? … yes
✔ Choose the test environment that will be used for testing › node
✔ Do you want Jest to add coverage reports? … yes
✔ Automatically clear mock calls and instances between every test? … yes

✏️  Modified /../demo-typescript/package.json

📝  Configuration file created at /../demo-typescript/jest.config.js

jest.config.js can look like this:

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

module.exports = {
  // 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_rs",

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

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

  // 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: 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: {},

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

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

  // 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: "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__/**/*.[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: 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: "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: {
  //   "^.+\\.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: true,

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

---

Config file can also be created via ts-jest:

$ npx ts-jest config:init

...but first you need to install ts-jest:

$ npm install jest typescript ts-jest --save-dev 

ts-jest creates jest.config.js file with the following content:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

If jest.config.js already exists, the previous command will fail with this error message:

ts-jest[cli] (FATAL) Configuration file jest.config.js already exists.


To see the list of all Jest options:

$ npx jest --help
Usage: jest [--config=<pathToConfigFile>] [TestPathPattern]

Options:

  --help, -h                    Show help                              [boolean]
  --version, -v                 Print the version and exit             [boolean]
  --all                         The opposite of `onlyChanged`. If `onlyChanged`
                                is set by default, running jest with `--all`
                                will force Jest to run all tests instead of
                                running only tests related to changed files.
  --automock                    Automock all files by default.         [boolean]
  --bail, -b                    Exit the test suite immediately after `n` number
                                of failing tests.
  --browser                     Respect the "browser" field in package.json when
                                resolving modules. Some packages export
                                different versions based on whether they are
                                operating in node.js or a browser.     [boolean]
  --cache                       Whether to use the transform cache. Disable the
                                cache using --no-cache.                [boolean]
  --cacheDirectory              The directory where Jest should store its cached
                                dependency information.                 [string]
  --changedFilesWithAncestor    Runs tests related to the current changes and
                                the changes made in the last commit. Behaves
                                similarly to `--onlyChanged`.          [boolean]
  --changedSince                Runs tests related to the changes since the
                                provided branch. If the current branch has
                                diverged from the given branch, then only
                                changes made locally will be tested. Behaves
                                similarly to `--onlyChanged`.           [string]
  --ci                          Whether to run Jest in continuous integration
                                (CI) mode. This option is on by default in most
                                popular CI environments. It will  prevent
                                snapshots from being written unless explicitly
                                requested.            [boolean] [default: false]
  --clearCache                  Clears the configured Jest cache directory and
                                then exits. Default directory can be found by
                                calling jest --showConfig              [boolean]
  --clearMocks                  Automatically clear mock calls and instances
                                between every test. Equivalent to calling
                                jest.clearAllMocks() between each test.[boolean]
  --collectCoverage             Alias for --coverage.                  [boolean]
  --collectCoverageFrom         A glob pattern relative to <rootDir> matching
                                the files that coverage info needs to be
                                collected from.                         [string]
  --collectCoverageOnlyFrom     Explicit list of paths coverage will be
                                restricted to.                           [array]
  --color                       Forces test results output color highlighting
                                (even if stdout is not a TTY). Set to false if
                                you would like to have no colors.      [boolean]
  --colors                      Alias for `--color`.                   [boolean]
  --config, -c                  The path to a jest config file specifying how to
                                find and execute tests. If no rootDir is set in
                                the config, the directory containing the config
                                file is assumed to be the rootDir for the
                                project.This can also be a JSON encoded value
                                which Jest will use as configuration.   [string]
  --coverage                    Indicates that test coverage information should
                                be collected and reported in the output.
                                                                       [boolean]
  --coverageDirectory           The directory where Jest should output its
                                coverage files.                         [string]
  --coveragePathIgnorePatterns  An array of regexp pattern strings that are
                                matched against all file paths before executing
                                the test. If the file pathmatches any of the
                                patterns, coverage information will be skipped.
                                                                         [array]
  --coverageReporters           A list of reporter names that Jest uses when
                                writing coverage reports. Any istanbul reporter
                                can be used.                             [array]
  --coverageThreshold           A JSON string with which will be used to
                                configure minimum threshold enforcement for
                                coverage results                        [string]
  --debug                       Print debugging info about your jest config.
                                                                       [boolean]
  --detectLeaks                 **EXPERIMENTAL**: Detect memory leaks in tests.
                                After executing a test, it will try to garbage
                                collect the global object used, and fail if it
                                was leaked            [boolean] [default: false]
  --detectOpenHandles           Print out remaining open handles preventing Jest
                                from exiting at the end of a test run.
                                                      [boolean] [default: false]
  --env                         The test environment used for all tests. This
                                can point to any file or node module. Examples:
                                `jsdom`, `node` or `path/to/my-environment.js`
                                                                        [string]
  --errorOnDeprecated           Make calling deprecated APIs throw helpful error
                                messages.             [boolean] [default: false]
  --expand, -e                  Use this flag to show full diffs instead of a
                                patch.                                 [boolean]
  --filter                      Path to a module exporting a filtering function.
                                This method receives a list of tests which can
                                be manipulated to exclude tests from running.
                                Especially useful when used in conjunction with
                                a testing infrastructure to filter known broken
                                tests.                                  [string]
  --findRelatedTests            Find related tests for a list of source files
                                that were passed in as arguments. Useful for
                                pre-commit hook integration to run the minimal
                                amount of tests necessary.             [boolean]
  --forceExit                   Force Jest to exit after all tests have
                                completed running. This is useful when resources
                                set up by test code cannot be adequately cleaned
                                up.                                    [boolean]
  --globalSetup                 The path to a module that runs before All Tests.
                                                                        [string]
  --globalTeardown              The path to a module that runs after All Tests.
                                                                        [string]
  --globals                     A JSON string with map of global variables that
                                need to be available in all test environments.
                                                                        [string]
  --haste                       A JSON string with map of variables for the
                                haste module system                     [string]
  --init                        Generate a basic configuration file    [boolean]
  --json                        Prints the test results in JSON. This mode will
                                send all other test output and user messages to
                                stderr.                                [boolean]
  --lastCommit                  Run all tests affected by file changes in the
                                last commit made. Behaves similarly to
                                `--onlyChanged`.                       [boolean]
  --listTests                   Lists all tests Jest will run given the
                                arguments and exits. Most useful in a CI system
                                together with `--findRelatedTests` to determine
                                the tests Jest will run based on specific files
                                                      [boolean] [default: false]
  --logHeapUsage                Logs the heap usage after every test. Useful to
                                debug memory leaks. Use together with
                                `--runInBand` and `--expose-gc` in node.
                                                                       [boolean]
  --mapCoverage                 Maps code coverage reports against original
                                source code when transformers supply source
                                maps.

                                DEPRECATED                             [boolean]

  --maxConcurrency              Specifies the maximum number of tests that are
                                allowed to runconcurrently. This only affects
                                tests using `test.concurrent`.
                                                           [number] [default: 5]
  --maxWorkers, -w              Specifies the maximum number of workers the
                                worker-pool will spawn for running tests. This
                                defaults to the number of the cores available on
                                your machine. (its usually best not to override
                                this default)                           [number]
  --moduleDirectories           An array of directory names to be searched
                                recursively up from the requiring module's
                                location.                                [array]
  --moduleFileExtensions        An array of file extensions your modules use.
                                If you require modules without specifying a
                                file extension, these are the extensions Jest
                                will look for.                           [array]
  --moduleNameMapper            A JSON string with a map from regular
                                expressions to module names that allow to stub
                                out resources, like images or styles with a
                                single module                           [string]
  --modulePathIgnorePatterns    An array of regexp pattern strings that are
                                matched against all module paths before those
                                paths are to be considered "visible" to the
                                module loader.                           [array]
  --modulePaths                 An alternative API to setting the NODE_PATH env
                                variable, modulePaths is an array of absolute
                                paths to additional locations to search when
                                resolving modules.                       [array]
  --noStackTrace                Disables stack trace in test results output
                                                                       [boolean]
  --notify                      Activates notifications for test results.
                                                                       [boolean]
  --notifyMode                  Specifies when notifications will appear for
                                test results.
                                            [string] [default: "failure-change"]
  --onlyChanged, -o             Attempts to identify which tests to run based on
                                which files have changed in the current
                                repository. Only works if you're running tests
                                in a git or hg repository at the moment.
                                                                       [boolean]
  --onlyFailures, -f            Run tests that failed in the previous execution.
                                                                       [boolean]
  --outputFile                  Write test results to a file when the --json
                                option is also specified.               [string]
  --passWithNoTests             Will not fail if no tests are found (for example
                                while using `--testPathPattern`.)
                                                      [boolean] [default: false]
  --preset                      A preset that is used as a base for Jest's
                                configuration.                          [string]
  --prettierPath                The path to the "prettier" module used for
                                inline snapshots.                       [string]
  --projects                    A list of projects that use Jest to run all
                                tests of all projects in a single instance of
                                Jest.                                    [array]
  --reporters                   A list of custom reporters for the test suite.
                                                                         [array]
  --resetMocks                  Automatically reset mock state between every
                                test. Equivalent to calling jest.resetAllMocks()
                                between each test.                     [boolean]
  --resetModules                If enabled, the module registry for every test
                                file will be reset before running each
                                individual test.                       [boolean]
  --resolver                    A JSON string which allows the use of a custom
                                resolver.                               [string]
  --restoreMocks                Automatically restore mock state and
                                implementation between every test. Equivalent to
                                calling jest.restoreAllMocks() between each
                                test.                                  [boolean]
  --rootDir                     The root directory that Jest should scan for
                                tests and modules within.               [string]
  --roots                       A list of paths to directories that Jest should
                                use to search for files in.              [array]
  --runInBand, -i               Run all tests serially in the current process
                                (rather than creating a worker pool of child
                                processes that run tests). This is sometimes
                                useful for debugging, but such use cases are
                                pretty rare.                           [boolean]
  --runTestsByPath              Used when provided patterns are exact file
                                paths. This avoids converting them into a
                                regular expression and matching it against every
                                single file.          [boolean] [default: false]
  --runner                      Allows to use a custom runner instead of Jest's
                                default test runner.                    [string]
  --setupFiles                  A list of paths to modules that run some code
                                to configure or set up the testing environment
                                before each test.                        [array]
  --setupFilesAfterEnv          A list of paths to modules that run some code
                                to configure or set up the testing framework
                                before each test                         [array]
  --showConfig                  Print your jest config and then exits. [boolean]
  --silent                      Prevent tests from printing messages through the
                                console.                               [boolean]
  --skipFilter                  Disables the filter provided by --filter. Useful
                                for CI jobs, or local enforcement when fixing
                                tests.                                 [boolean]
  --snapshotSerializers         A list of paths to snapshot serializer modules
                                Jest should use for snapshot testing.    [array]
  --testEnvironment             Alias for --env                         [string]
  --testEnvironmentOptions      Test environment options that will be passed to
                                the testEnvironment. The relevant options depend
                                on the environment.                     [string]
  --testFailureExitCode         Exit code of `jest` command if the test run
                                failed                                  [string]
  --testLocationInResults       Add `location` information to the test results
                                                      [boolean] [default: false]
  --testMatch                   The glob patterns Jest uses to detect test
                                files.                                   [array]
  --testNamePattern, -t         Run only tests with a name that matches the
                                regex pattern.                          [string]
  --testPathIgnorePatterns      An array of regexp pattern strings that are
                                matched against all test paths before executing
                                the test. If the test path matches any of the
                                patterns, it will be skipped.            [array]
  --testPathPattern             A regexp pattern string that is matched against
                                all tests paths before executing the test.
                                                                         [array]
  --testRegex                   A string or array of string regexp patterns that
                                Jest uses to detect test files.          [array]
  --testResultsProcessor        Allows the use of a custom results processor.
                                This processor must be a node module that
                                exports a function expecting as the first
                                argument the result object.             [string]
  --testRunner                  Allows to specify a custom test runner. The
                                default is  `jasmine2`. A path to a custom test
                                runner can be provided:
                                `<rootDir>/path/to/testRunner.js`.      [string]
  --testSequencer               Allows to specify a custom test sequencer. The
                                default is `@jest/test-sequencer`. A path to a
                                custom test sequencer can be provided:
                                `<rootDir>/path/to/testSequencer.js`    [string]
  --testURL                     This option sets the URL for the jsdom
                                environment.                            [string]
  --timers                      Setting this value to fake allows the use of
                                fake timers for functions such as setTimeout.
                                                                        [string]
  --transform                   A JSON string which maps from regular
                                expressions to paths to transformers.   [string]
  --transformIgnorePatterns     An array of regexp pattern strings that are
                                matched against all source file paths before
                                transformation.                          [array]
  --unmockedModulePathPatterns  An array of regexp pattern strings that are
                                matched against all modules before the module
                                loader will automatically return a mock for
                                them.                                    [array]
  --updateSnapshot, -u          Use this flag to re-record snapshots. Can be
                                used together with a test suite pattern or with
                                `--testNamePattern` to re-record snapshot for
                                test matching the pattern              [boolean]
  --useStderr                   Divert all output to stderr.           [boolean]
  --verbose                     Display individual test results with the test
                                suite hierarchy.                       [boolean]
  --watch                       Watch files for changes and rerun tests related
                                to changed files. If you want to re-run all
                                tests when a file has changed, use the
                                `--watchAll` option.                   [boolean]
  --watchAll                    Watch files for changes and rerun all tests. If
                                you want to re-run only the tests related to the
                                changed files, use the `--watch` option.
                                                                       [boolean]
  --watchPathIgnorePatterns     An array of regexp pattern strings that are
                                matched against all paths before trigger test
                                re-run in watch mode. If the test path matches
                                any of the patterns, it will be skipped. [array]
  --watchman                    Whether to use watchman for file crawling.
                                Disable using --no-watchman.           [boolean]

Documentation: https://jestjs.io/


---


const greeter = require('../src/modules/greeter');

test('greeter ', () => {
  expect(greeter("ABC")).toBe('Hello, ABC');
});


Intellisense will mark an error on test with following message:

Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`  and then add `jest` or `mocha` to the types field in your tsconfig.ts(2582)

So all we have to do is:

$ npm install @types/jest --save-dev

Using Jest with TypeScript


Where to place Jest test file?

Right next to the source file that contains SUT (Subject Under Test).

Organizing Tests in Jest

Unit tests run against specific lines of code. So it makes sense to place them right next to that code. 
|- /main|  |- index.js|  |- index.test.js


Why I Recommend Unit Tests in the Src Folder

The approach I like to take is that you throw the unit tests right in the app and src directories with all the other application code. Why I do this? There are basically three reasons:
  • You can easily ensure all javascript files have a corresponding test file.
  • You can easily switch between the test file and app code file.
  • It's easier for command line generators to create code and spec files for you this way.
Jest documentation is allowing it [source]:

(...) if you have tests in source files named with .t.js extension (...)

How to set up Jest & Enzyme like a boss

testMatch tells Jest which files it will test. I pass in 2 configurations here, one being test all files in any folder named __tests__ or test all files that end with spec.js|.jsx or test.js|.jsx 
Before we run a test, we need to create one. So let’s start. In your app/src/ folder create a file called WelcomeMessage.js. In the same folder create a file called WelcomeMessage.test.js

We can tell TS compiler not to compile test files/folders by specifying exclude property in tsconfig.json:

  "exclude": [
    "./__tests__/",
    "**/*.test.ts"
  ]

How to test some function for a set of inputs and against the set of outputs?

Jest looping through dynamic test cases



My demo project on GitHub: https://github.com/BojanKomazec/jest-demo-node-ts

No comments: