Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

dts-jest

ikatyang1.4kMIT26.0.2TypeScript support: included

A preprocessor for Jest to snapshot test TypeScript declaration (.d.ts) files

jest, jest-transform, test, typescript, typescript-declarations

readme

dts-jest

npm build coverage

A preprocessor for Jest to snapshot test TypeScript declaration (.d.ts) files

Changelog

Install

# using npm
npm install --save-dev dts-jest jest typescript

# using yarn
yarn add --dev dts-jest jest typescript
  • require jest@>=28 and typescript@>=4

    | dts-jest | jest | typescript | | -------- | -------- | ---------- | | 26 | >=28 | >=4 | | 25 | >=28 <30 | >=2.3 <5 | | 24 | 27 | >=2.3 <5 | | 23 | >=22 <27 | >=2.3 <5 |

Usage

Modify your Jest config so that looks something like:

(./package.json)

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "moduleFileExtensions": ["ts", "js", "json"],
    "testRegex": "/dts-jest/.+\\.ts$",
    "transform": {"/dts-jest/.+\\.ts$": "dts-jest/transform"}
  }
}

This setup allow you to test files **/dts-jest/**/*.ts via dts-jest.

Writing Tests

The test cases must start with a comment @dts-jest, and the next line should be an expression that you want to test its type or value.

(./dts-jest/example.ts)

// @dts-jest:pass:snap
Math.max(1);

// @dts-jest:pass
Math.min(1, 2, 3); //=> 1

// @dts-jest:fail:snap
Math.max('123');

// @ts-expect-error:snap
Math.max('123');

Patterns

Patterns for Testing

// @dts-jest[flags] [description]
expression //=> expected

// @ts-expect-error[flags] [description]
expression //=> expected

Note: @ts-expect-error is treated as an alias of @dts-jest:fail in dts-jest.

Patterns for Grouping

Test cases after this pattern will be marked as that group.

// @dts-jest:group[flag] [description]

If you need a block scope for your tests you can use a Block Statement.

// @dts-jest:group[flag] [description]
{
  // your tests
}

Patterns for File-Level Config

File-level config uses the first comment to set, only docblock will be detected.

/** @dts-jest [action:option] ... */
  • action:
    • enable: set to true
    • disable: set to false
  • option:
    • test-type: test_type option in configs
    • test-value: test_value option in configs

Testing

It's recommended you to run Jest in watching mode via --watch flag.

npm run test -- --watch

NOTE: If you had changed the version of dts-jest, you might have to use --no-cache flag since Jest may use the older cache.

After running the example tests with npm run test, you'll get the following result:

 PASS  tests/example.ts
  Math.max(1)
    ✓ (type) should not throw error
    ✓ (type) should match snapshot
  Math.max('123')
    ✓ (type) should throw error
    ✓ (type) should match snapshot
  Math.min(1, 2, 3)
    ✓ (type) should not throw error

Snapshot Summary
 › 2 snapshots written in 1 test suite.

Test Suites: 1 passed, 1 total
Tests:       5 passed, 5 total
Snapshots:   2 added, 2 total
Time:        0.000s
Ran all test suites.

Since snapshot testing will always pass and write the result at the first time, it's reommended you to use :show flag to see the result first without writing results.

(./dts-jest/example.ts)

// @dts-jest:pass:show
Math.max(1);

// @dts-jest:fail:show
Math.max('123');

// @dts-jest:pass
Math.min(1, 2, 3); //=> 1
 PASS  dts-jest/example.ts
  Math.max(1)
    ✓ (type) should show report
    ✓ (type) should not throw error
  Math.max('123')
    ✓ (type) should show report
    ✓ (type) should throw error
  Math.min(1, 2, 3)
    ✓ (type) should not throw error

Test Suites: 1 passed, 1 total
Tests:       5 passed, 5 total
Snapshots:   0 total
Time:        0.000s
Ran all test suites.

  console.log dts-jest/example.ts:2

    Inferred

      Math.max(1)

    to be

      number

  console.log dts-jest/example.ts:5

    Inferring

      Math.max('123')

    but throw

      Argument of type '"123"' is not assignable to parameter of type 'number'.

Configs

Configs are in _dts_jest_ field of Jest config globals.

There are several options

  • test_type
  • test_value
  • enclosing_declaration
    • default: false
    • unwrap type alias
  • typescript
    • default: typescript (node resolution)
    • specify which path of typescript to use
    • <cwd> available
  • compiler_options
    • default: {}
    • specify which path of tsconfig.json (string) or compilerOptions (object) (deprecated, does not support typeRoots for object) to use
  • type_format_flags
    • default: ts.TypeFormatFlags.NoTruncation
    • specify type format
  • transpile
    • default: true
    • transpile code before testing, only affect tests that needs to test value
    • transpiling code will cause line number incorrect, it's better to disable this option if possible

For example:

(./package.json)

{
  "jest": {
    "globals": {
      "_dts_jest_": {
        "compiler_options": {
          "strict": true,
          "target": "es6"
        }
      }
    }
  }
}

Generate diff-friendly snapshots

Originally, snapshots and source content are in different files, it is hard to check their difference before/after, so here comes the dts-jest-remap for generating diff-friendly snapshots.

(./tests/example.ts)

// @dts-jest:snap
Math.max(1, 2, 3);

(./tests/__snapshots__/example.ts.snap) note this file is generated by Jest

// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Math.max(1, 2, 3) 1`] = `"number"`;

This command will combine both snapshots and source content in one file:

dts-jest-remap ./tests/example.ts --outDir ./snapshots

(./snapshots/example.ts)

// @dts-jest:snap -> number
Math.max(1, 2, 3);
Usage: dts-jest-remap [--outDir <path>] [--rename <template>] <TestFileGlob> ...

Options:
  --check, -c          Throw error if target content is different from output
                       content                                         [boolean]
  --help, -h           Show help                                       [boolean]
  --listDifferent, -l  Print the filenames of files that their target content is
                       different from output content                   [boolean]
  --outDir, -o         Redirect output structure to the directory       [string]
  --rename, -r         Rename output filename using template {{variable}},
                       available variable: filename, basename, extname  [string]
  --typescript, -t     Specify which TypeScript source to use           [string]
  --version, -v        Show version number                             [boolean]

Reporter

If you'd like to know which typescript you are using, add dts-jest/reporter to your Jest reporters, for example:

{
  "reporters": [
    "default",
    "dts-jest/reporter"
  ]
}

It'll show the TS version and path after testing:

[dts-jest] using TypeScript v0.0.0 from path/to/typescript

FAQ

  • Compiler option 'lib' requires a value of type list
    • Arrays in jest > globals > _dts_jest_ will be transformed into objects.
    • Consider to use setupFiles to set configs (globals._dts_jest_ = { ... }).
    • See jest#2093 for details.
  • Debug Failure
    • This is mostly caused by regex literal due to the printer bug TypeScript#18071 (fixed in TS v2.6).
    • Workaround: use regex instance instead, e.g. new RegExp('something').

Development

# lint
yarn run lint

# test
yarn run test

# build
yarn run build
  • dtslint: A utility built on TSLint for linting TypeScript declaration (.d.ts) files
  • typings-checker: Positive and negative assertions about TypeScript types and errors

License

MIT © Ika

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

26.0.2 (2024-02-25)

  • v26.0.1 has been unpublished due to missing files on npm, publish again to address the issue

26.0.1 (2024-02-25)

Bug Fixes

26.0.0 (2023-04-07)

⚠ BREAKING CHANGES

  • TypeScript 4 is now the minimal supported version

Features

25.0.0 (2022-05-14)

Features

BREAKING CHANGES

  • Jest 28 is now the minimal supported version

24.0.0 (2021-05-30)

Features

BREAKING CHANGES

  • Jest 27 is now the minimal supported version

23.3.0 (2020-08-12)

Features

23.2.0 (2020-07-29)

Features

23.1.0 (2020-06-27)

Features

  • support @ts-expect-error (60451a3)

23.0.0 (2019-04-13)

Chores

Features

BREAKING CHANGES

  • drop support for jest < 22
  • drop support for node v4

22.0.4 (2018-06-27)

Bug Fixes

22.0.3 (2017-09-05)

Bug Fixes

  • deps: update dependency pretty-format to ^21.0.0 (#88) (3721a48)
  • peerDeps: accept jest ^21.0.0 (#89) (fc47496)

22.0.2 (2017-09-04)

Bug Fixes

  • options: add <cwd> placeholder for typescript option to better describe its path (#86) (a003a31)

22.0.1 (2017-09-01)

Bug Fixes

  • runtime: show 1-based line number (#82) (de4c6aa)

22.0.0 (2017-08-31)

Bug Fixes

  • deps: jest peerDeps should allow ^20.0.0 (1a24239)
  • report unmatched diagnostic (#52) (4ab0f86)
  • deps: update peerDeps typescript to ^2.3.0 (c075dd2)

Features

BREAKING CHANGES

  • deps: drop TS < v2.3
  • transform-actual: remove transformer transform-actual as it currently combined with transform
  • remap: [API] remap(...)
    • before
      • snapshot_content
        • allow string (raw content from *.snap)
        • allow Record<string, string> (unparsed content from *.snap)
    • after
      • snapshot_content
        • allow string (raw content from *.snap)
        • allow Record<string, string> (parsed content from *.snap)
  • remap-cli: rename bin from dts-jest-remap-snapshot to dts-jest-remap
    • input using source file instead of snapshot file, e.g.
      • before: ./__snapshots__/example.ts.snap
      • after: ./example.ts
    • output content does not print to stdout now, use --outDir and --rename to specify output path instead
  • configs: replace config value with config literal
    • Before
      {
        "target": 5 // ts.ScriptTarget.ESNext
      }
    • After
      {
        "target": "esnext"
      }
  • flags: redefine flag
    • type tests
      • @dts-jest -> @dts-jest:snapshot
      • @dts-jest:snap -> @dts-jest:snapshot
      • @dts-jest:pass -> @dts-jest:pass:snapshot
      • @dts-jest:fail -> @dts-jest:fail:snapshot
    • actual tests
      • @dts-jest + //=> value -> //=> :no-error
      • @dts-jest:snap + //=> value -> //=> :no-error
      • @dts-jest:show + //=> value -> //=> ?
      • @dts-jest:pass + //=> value -> //=> value
      • @dts-jest:fail + //=> value -> //=> :error

21.0.0 (2017-08-18)

Features

  • deps: move typescript to peerDependecies (#38) (e9800f1)

BREAKING CHANGES

  • deps: TypeScript now has to be installed manually so that you can choose which version to use

  • version: This project now DOES NOT use the same versioning as Jest

v20.5.1 (2017-06-30)

🚀 New Feature

  • allow using snapshot-content object for remap-snapshot
  • allow specifying snapshot filename for remap-snapshot so as to handle cache

v20.5.0 (2017-06-30)

🚀 New Feature

  • Add remap-snapshot to generate diff-friendly snapshots

v20.4.1 (2017-06-24)

🐛 Bug Fix

  • Fix transpile error for actual test

v20.4.0 (2017-06-24)

🚀 New Feature

  • Add actual test transformer (dts-jest/transform-actual) with //=> value comment

v20.3.1 (2017-06-21)

🐛 Bug Fix

  • Fix indentation for description of grouped test

v20.3.0 (2017-06-21)

🚀 New Feature

  • Add group flag to categorize test cases
  • Add default flags ( :test, :shot ) to show its explicit flag
  • Allow to set flags with any order, e.g. :show:only, :only:show

🐛 Bug Fix

  • Remove unnecessary leading spaces in expressions (dedent)

v20.2.0 (2017-06-20)

🚀 New Feature

  • Add flags ( :pass, :fail, :only:pass, :only:fail ) to assert its result

v20.1.0 (2017-06-13)

💥 Breaking Change

  • Use same MAJOR version as Jest
  • Remove server since tests should be separated

🚀 New Feature

  • Add config type_format
  • Display description in :show

v20.0.6 (2017-06-10)

🐛 Bug Fix

  • Fix transforming for template token

v20.0.4 (2017-06-09)

🐛 Bug Fix

  • Fix unexpected filenames

🏠 Internal

  • Use POST for modification actions

v20.0.3 (2017-06-03)

💥 Breaking Change

  • setup a server for initializing TS source file at once
  • remove useless config type_detail, type_format, snapshot_formatter

🚀 New Feature

  • allow to use <rootDir> in config tsconfig

v20.0.2 (2017-05-16)

🐛 Bug Fix

  • Fix missing config

v20.0.1 (2017-05-16)

🚀 New Feature

  • detect unattachable triggers
  • allow to customize :show message with reporter option
  • allow to customize inferred type with type_detail and type_format option
  • allow to customize snapshot content with snapshot_formatter option

🏠 Internal

  • rewrite for better user experience about cache

v20.0.0 (2017-05-14)

🚀 New Feature

  • Use same MAJOR.MINOR version as Jest

📝 Documentation

  • Fix image urls in README.md

v1.0.5 (2017-05-13)

🐛 Bug Fix

  • Fix dependency

v1.0.4 (2017-05-13)

🚀 New Feature

  • Release first version