Vitest's behavior shows variance when compared to compiled JavaScript

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!

Answer №1

Using Jest, I was able to find a solution to my issue. It required the installation of several Babel plugins to get everything working smoothly.

module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    "@babel/preset-typescript",
  ],
  plugins: [
    ["@babel/plugin-proposal-decorators", { version: "2023-05" }],
    ["@babel/plugin-transform-flow-strip-types"],
    ["@babel/plugin-transform-class-properties"],
    ["@babel/plugin-transform-class-static-block"],
  ],
};

I also stumbled upon a helpful post that sheds light on why decorators may not function correctly with Vitest.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying data from an Angular subscription in a user interface form

I am attempting to transfer these item details to a form, but I keep encountering undefined values for this.itemDetails.item1Qty, etc. My goal is to display them in the Form UI. this.wareHouseGroup = this.formBuilder.group({ id: this.formBuilder.contr ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...

Implementing try-catch logic for element visibility in Playwright using TypeScript poses limitations

There is a specific scenario I need to automate where if the title of a page is "Sample title", then I must mark the test as successful. Otherwise, if that condition is not met, I have to interact with another element on the page and verify if the title ch ...

Error in Typescript occurring with a custom typography element

I recently developed a simple typography component for my React project and it's causing a Typescript error that's puzzling me a bit. Typography Component Code import clsx from 'clsx'; const sizeVariants = { h1: 'h1', ...

When working with TypeScript, encountering an error involving an array containing an index signature

When attempting to change an object's type to a generic array using the as keyword, I encountered an error. interface TestType { action: TestGeneric<number>[] } type TestGeneric<T> = { [key: string]: T } const func = () => { ...

Deleting the First Item from an Array in Typescript using Angular

Clicking my Button in .html <button (click)="deleteFirst()">Delete First</button> My array setup and removal function in .ts: people = [ {first: "Tom", last: "Brown"}, {first: "Ben", last: &qu ...

A Guide to Filtering MongoDB Data Using Array Values

I am trying to extract specific data from a document in my collection that contains values stored in an array. { "name": "ABC", "details": [ {"color": "red", "price": 20000}, {" ...

Having trouble installing the gecko driver for running protractor test scripts on Firefox browser

Looking to expand my skills with the "Protractor tool", I've successfully run test scripts in the "Chrome" browser. Now, I'm ready to tackle running tests in "Firefox," but I know I need to install the "gecko driver." Can anyone guide me on how t ...

Silence in Angular NGRX Effects

I am currently utilizing ngrx Effects to send a http call to my server, but for some reason the effect is not triggered. My goal is to initiate the http call when the component loads. I have tried using store.dispatch in ngOnInit, however, nothing seems to ...

Leveraging AWS CDK to seamlessly integrate an established data pipeline into your infrastructure

I currently have a data pipeline set up manually, but now I want to transition to using CDK code for management. How can I achieve this using the AWS CDK TypeScript library to locate and manage this data pipeline? For example, with AWS SNS, we can utilize ...

Attempting to search for an item by its id within a local json file using Angular

I have a local JSON file containing Kitchen types. I created the KitchenTypesService with two functions inside, GET and FIND(ID). The GET function is working fine, but the FIND function is not working and displaying an error "ERROR TypeError: Unable to lif ...

What is the best way to evaluate typing into an input field?

My objective is to test the 'typing' functionality in an input element. The aim is to insert a value into the input element, verify that its binding successfully captures the value, and observe the entered value within the input element. Below i ...

gather and handle data from the shared interface between different parts

I have two different paths. One is for products and the other is for products-cart. I want to use a shared ts file for both to store the product and cart information in an array. However, I am encountering an issue. I am unable to make any changes or trans ...

Utilize Angular's $state service within a configuration setting to automatically redirect to a specific state using an interceptor

I'm working with restangular and have set up an interceptor to handle 401 responses by redirecting to another state. The issue is that angular only allows the injection of providers, not services, in config. Is there a way to access the $state: ng.u ...

The function did not return a Promise or value as expected when using async and await

    I have been working on implementing this code structure for my cloud functions using httpRequest. It has worked seamlessly with those httpRequest functions in the past. However, I recently encountered an error when trying to use it with the OnWrite ...

How to conditionally import various modules in Next.js based on the environment

Having two modules 'web,ts' and 'node.ts' that share similar interfaces can be challenging. The former is designed to operate on the client side and edge environment, while the latter depends on node:crypto. To simplify this setup, I a ...

Angular jsonp.get request was denied despite receiving a status code of 200 indicating success

I have been attempting to access my basic web API created in Jersey, which returns the following data: [ { "id": 1, "name": "Facebook", "userName": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f4 ...

What is causing the "excessive stack depth" error in this JSX code?

Exploring Next.js' TypeScript (4.2.3) functionality, I am utilizing it to compile the React component provided below. const Component = (): JSX.Element => { const categories = ['Fruit', 'Vegetables']; return ( <ul> ...

Looking to start using WebDriverIO and Typescript with the WDIO wizard? Here's how to get it

I'm in the process of setting up a WebdriverIO project using TypeScript and Cucumber. I followed the steps provided by the wizard, which was pretty straightforward. I opted for Cucumber, TypeScript, and the page object model. This setup created a tes ...

Angular: Generating a fresh instance of an object monthly

My goal is to create an object called "Activity" in Angular 8, which will automatically generate an activity for each month upon creation. For example: export class Activity { activityID = string; activityName = string; startDate = Date ...