Challenge
Currently, I am developing a package that relies on decorators to initialize class object properties. The specific decorator is expected to set the name property of the class.
// index.ts
const Property = (_target: any, key: any) => {
}
class Student {
@Property
name!: string;
age!: number;
}
console.log(Object.getOwnPropertyNames(new Student()) // Outputs ["name"]
Testing this behavior in Vitest has led to unexpected results. When calling
Object.getOwnPropertyNames(new Student())
, an empty array is returned instead of the expected result.
// index.spec.ts
describe("Test decorator", () => {
class Student {
@Property
name!: string;
}
it("Decorator initializes value correctly", () => {
expect(Object.getOwnPropertyNames(student)).toEqual(
expect.arrayContaining(["name"]) // Test fails
);
});
})
Setup
- node:
v20.5.1
- typescript:
v5.3.3
# package.json
{
"devDependencies": {
"ts-node": "^10.9.2",
"typescript": "^5.3.3",
"vitest": "^1.2.0"
}
}
# tsconfig.json
{
"compilerOptions": {
/* Language and Environment */
"target": "ES6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
/* Emit */
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
/* Interop Constraints */
"esModuleInterop"": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
"forceConsistentCasingInFileNames"
Attempted Solutions
I initially suspected that the issue lies with the initialization of tsconfig.json
for Vitest. Despite altering the path manually in vitest.config.ts
, the problem persisted.
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
typecheck: {
tsconfig: "./tsconfig.json",
},
},
});
Further exploration into documentation and online resources yielded no relevant solutions. At this point, I am unsure how to proceed and would appreciate any guidance or suggestions!