This gist
is designed to explain how to configure a project where you have your test code separated from your codebase. The project file structure looks a bit like this:
project
├─┬ lib # could be src
│ ├── globals.d.ts # source code specific type declarations
│ └── index.ts
├─┬ tests
│ ├── index.test.ts
│ └── jest-extended.d.ts # could be globals.d.ts if you have other test declarations to add
├── .eslintignore
├── .eslintrc.js # remember to set `env["jest/globals"] = true` for test files & load `eslint-plugin-jest`
├── jest.config.js
├── package.json
├── README.md
├── tsconfig.eslint.json
├── tsconfig.jest.json
└── tsconfig.json
There are 3 steps:
tsconfig.jest.json
: Extend your Typescript configuration to include your tests directory for types & compilationjest.config.js
: Configurets-jest
to recognize your jest specific configuration & compilation directives. This also includes thejest-extended/all
definition as an array entry forsetupFilesAfterEnv
.jest-extended.d.ts
: Add a types reference entry to declare jest-extended types for the Typescript compiler
If you follow the jest
recommendations for unit testing to have tests as "close to your source as possible", this likely means your test code is inside your src/
or lib/
folder under __tests__/
. If so, your test files are already included by your tsconfig.json[include]
definition. You can still follow these instructions but note you will want to place your jest-extended reference outside of your source code directory and make sure to include it explicitly in tsconfig.jest.json[include]
array.
Make sure you have read all the embedded comments in the configuration files below! The jest.config.json#[projects]
configuration can be problematic.
It can act a bit funny with type declaration files that are not named globals.d.ts
and not in your base tsconfig.json
. This does not mean ts-jest
will not work. If you open the declaration file while the file is open, it will magically resolve. This is a flaw in vscode since it take some time to cache types into its own directory for its real-time compiler.