I am utilizing Mocha/Chai with TS-Node to conduct unit tests on a React/TypeScript application developed with Vite.
While most tests are running smoothly, I am encountering difficulties with tests that require access to type definitions from vite-env.d.ts
. The challenge lies in referencing these types for TypeScript to recognize when working through TS-Node.
Directory structure:
myProject/
src/
ts/
myModule.ts
vite-env.d.ts
test/
unit/
myModule.spec.ts
.mocharc.json
tsconfig.json
package.json
Configuration files:
// package.json
{
"type": "module",
"scripts": {
"test": "mocha --config test/.mocharc.json"
},
"devDependencies": {
"@types/chai": "^4.3.4",
"@types/mocha": "^10.0.1",
"chai": "^4.3.7",
"mocha": "^10.2.0",
"ts-node": "^10.9.1",
"typescript": "^4.9.3",
"vite": "^4.0.0"
}
}
// test/.mocharc.json
{
"loader": "ts-node/esm",
"extensions": [
"ts"
],
"spec": [
"test/**/*.spec.ts"
],
"watch-files": [
"src/vite-env.d.ts",
"src/ts/*.ts",
"test/**/*.spec.ts"
],
"experimental-json-modules": true
}
// test/tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext"
},
"ts-node": {
"esm": true
}
}
Vite type definitions:
// src/vite-env.d.ts
/// <reference types='vite/client' />
type MyCustomType= {
start: string,
end: string
};
Module under testing:
// src/ts/myModule.ts
function foo({ start, end }: MyCustomType): string {
// ...
}
export { foo };
Test file:
// test/unit/myModule.spec.ts
import 'mocha';
import { expect } from 'chai';
import { foo } from '../../src/ts/myModule.js';
describe("foo is awesome", () => {
it("works! :D", () => {
const bar = foo({ start: "", end: ""});
expect(bar).to.be.string;
});
});
Current error:
TSError: ⨯ Unable to compile TypeScript:
src/ts/myModule.ts:2:30 - error TS2304: Cannot find name 'MyCustomType'.
2 function foo({ start, end }: MyCustomType): string {
...
Adding the MyCustomType
definition directly into myModule.ts
resolves the issue. However, this approach would be cumbersome for numerous files that share the same type definitions.
Including "types": [ "src/vite-env.d.ts" ]
in the compilerOptions
does not seem to make any difference.
What steps can be taken to enable TS-Node to utilize the type definitions from vite-env.d.ts
?