File Structure
An important step in type testing is to take care that any accidental types do not leak into test files. The following strategies help to ensure isolation of your tests.
TSTyche is built to test projects of any size and complexity. To learn more, see the Introduction page.
Dedicated Directory
It is recommended to keep type test files in a dedicated directory. For instance, you can name it __typetests__
:
- MethodLikeKeys.tst.ts
- tsconfig.json
- MethodLikeKeys.ts
- package.json
- tsconfig.json
Here the root tsconfig.json
specifies the compiler configuration of the project. Extend from it and reuse the configuration for type testing:
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"strict": true,
"types": []
},
"include": ["./"],
"exclude": []
}
The above configuration prevents loading global scope typings from @types/*
packages and makes it easy to include only the files you need for type testing.
By convention, it is recommended to suffix the unit tests with .test.*
and the type tests with .tst.*
. The latter ones are only statically analyzed and are not meant to be executed, hence the missing e
in the suffix.
Shared Directory
It is also possible to keep unit and type test files in a single shared directory:
- MethodLikeKeys.tst.ts
- secondItem.test.ts
- tsconfig.json
- MethodLikeKeys.ts
- secondItem.ts
- package.json
- tsconfig.json
- tstyche.config.json
Remember to specify the types
list of the compilerOptions
. Keep it as minimal as possible to avoid any global typings leaking into your type tests:
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"strict": true,
"types": [] // prefer explicitly importing testing APIs
},
"include": ["./"],
"exclude": []
}
To use type testing assertions in unit tests, configure TSTyche to include the unit test files in the test run:
{
"testFileMatch": ["**/*.test.ts", "**/*.tst.ts"]
}
Next to Source Files
Isolation of type tests placed next to source files is complicated, but not impossible. A hypothetical project could look like this:
- MethodLikeKeys.ts
- MethodLikeKeys.tst.ts
- secondItem.ts
- secondItem.test.ts
- package.json
- tsconfig.json
- tsconfig.test.json
- tstyche.config.json
The references
field could be used to define the project in the root tsconfig.json
:
{
"compilerOptions": {
// ...
"composite": true
},
"include": ["./src"],
"exclude": ["**/*.test.*", "**/*.tst.*"],
"references": [{ "path": "./tsconfig.test.json" }]
}
And tsconfig.test.json
can extend it like this:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"strict": true,
"types": [] // prefer explicitly importing testing APIs
},
"exclude": []
}