Error: There was a problem trying to import the `.d.ts` file

Software Stack

  • Vue version 3.2.19
  • @vue/test-utils version 2.0.0-rc.15
  • Typescript version 4.1.6

Issue Description

Encountering an error when running the command

vue-cli-service test:unit --no-cache
.

Please refer to the TypeError screenshot

(link to Continuous Integration details https://github.com/baronkoko/vue-unit-tests-type-error/runs/3728921894?check_suite_focus=true)

The issue occurs when a Vue component, which is importing a TypeScript file from node modules, has another TypeScript file import.

Sample code from example.spec.ts:

import { shallowMount } from "@vue/test-utils";
import HelloWorld from "@/components/HelloWorld.vue";

describe("HelloWorld.vue", () => {
  it("should render full name", () => {
    const firstName = "Tailor";
    const lastName = "Cox";
    const wrapper = shallowMount(HelloWorld, {
      props: { firstName, lastName },
    });
    expect(wrapper.text()).toMatch(
      `${firstName.toUpperCase()} ${lastName.toUpperCase()}`
    );
  });
});

Code snippet from HelloWorld.vue:

<template>
  <div class="hello">
    <h1>{{ fullName }}</h1>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

import { FakeUtil } from "fake-utils-lib/src/fake-util";

export default defineComponent({
  name: "HelloWorld",
  props: {
    firstName: {
      type: String,
      default: "",
    },
    lastName: {
      type: String,
      default: "",
    },
  },
  computed: {
    fullName() {
      const util = new FakeUtil();

      return util.getFullNameCapitalized(this.firstName, this.lastName);
    },
  },
});
</script>

Content of fake-util.ts:

import { Helpers } from "./helpers";

export class FakeUtil {
  getFullNameCapitalized(firstName: string, lastName: string): string {
    return `${Helpers.capitalize(firstName)} ${Helpers.capitalize(lastName)}`;
  }
}

Code in helpers.ts:

export class Helpers {
  static capitalize(text: string): string {
    return text.toUpperCase();
  }
}

You can find the complete example at this GitHub repository

Possible solutions for the issue include:

  1. Add the extension to the imported file, for instance:

    // @ts-ignore

    import { Helpers } from "./helpers.ts";

  2. Enable isolatedModules in ts-jest within jest.config.js

    globals: { "ts-jest": { isolatedModules: true, }, },

However, enabling isolatedModules may cause SyntaxError issues, especially with optional chaining as shown here

If anyone can provide assistance with resolving this problem, it would be greatly appreciated.

Answer №1

Resolved the issue by compiling all external modules using Rollup in esm format and incorporating them

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

Vuetify: Mobile keyboard failing to focus on text field

I'm feeling completely lost with this issue. Here's the code snippet I'm struggling with: <template> <v-container> <v-row> <v-col cols='12'> <v-text-field ...

Is it possible to loop through each row in a table using Cypress and execute the same actions on every iteration?

I have a frontend built with html/typescript that features a table of variable length containing action buttons in one of the columns. I am looking to create a Cypress test that will click on the first button of the first row, carry out a specific task, an ...

When utilizing Typescript with React Reduxjs toolkit, there seems to be an issue with reading the state in useSelector. An error message is displayed indicating that the variable loggedIn

I have encountered an error while passing a state from the store.tsx file to the component. The issue lies in the const loggedIn where state.loggedIn.loggedIn is not recognized as a boolean value. Below is the code snippet for the component: import React ...

Angular is programmed to detect any alterations

Upon detecting changes, the NgOnChanges function triggers an infinite service call to update the table, a situation that currently perplexes me. Any assistance on this matter would be greatly appreciated. Many thanks. The TableMultiSortComponent functions ...

"Exploring the world of jest.doMock: A guide to mocking

Here is the code snippet I am testing: ... import data from '../data/mock.json'; // function is async export const something = async () => { try { ... if (!data) { throw 'error is here!'; } ...

Development of v-treeview expanding and collapsing feature

click here for image I have a v-treeview component in my Vue.js project that dynamically populates items and shows different modules when clicking on node children. I am trying to implement collapse and expand functionality so that only one node is expand ...

Vue3 - Quasar q-tabs do not maintain values between them

I am facing an issue while designing a screen to submit a form in modal using vue3 and quasar. I have organized the form components by tabulating them, but when I switch tabs, the current selection disappears, showing the old value when I return. However, ...

Using Jest and TypeScript to mock the return value of react-oidc-context

For our project, we utilize react-oidc-context to handle user authentication using oidc-client-ts under the hood. The useAuth function provided by react-oidc-context gives us access to important information such as isAuthenticated, isLoading, and the auth ...

Create a TypeScript interface that represents an object type

I have a Data Structure, and I am looking to create an interface for it. This is how it looks: const TransitReport: { title: string; client: string; data: { overdueReviews: number; outstandingCovenantBreaches ...

What is the process for parameterizing a tuple in coding?

In my scenario, I have a tuple with interrelated types. Specifically, it involves an extractor function that retrieves a value, which is then used as input for another function. What I envision conceptually looks like this code snippet, although it does n ...

Organize Laravel Vue components into separate JavaScript files for optimal performance

I am currently working on a Laravel project that has multiple front-ends depending on the logged-in user. In addition, there is a shared directory where common components like tables and modals are stored for use across different front-ends. My goal is t ...

Optimal method for writing to JSON file in NodeJS 10 and Angular 7?

Not sure if this question fits here, but it's really bothering me. Currently using Node v10.16.0. Apologies! With Angular 7, fs no longer functions - what is the optimal method to write to a JSON file? Importing a JSON file is now simple, but how ca ...

After transitioning to a different laptop, I encountered unexpected ES6 syntax errors while trying to compile my Vue project

I recently acquired a new laptop and encountered an issue. After pulling my Vue project from GitHub, I proceeded to run npm install, followed by npm run dev. ERROR Failed to compile with 1 errors 1:38:10 PM ...

How to transfer data using props through the ":to" attribute of a router link in Vue.js

I am facing an issue with creating a router-link in Vue and passing a route name as a prop. What I am trying to achieve is the following: <template> <div> <router-link :to="myProps">Login</router-link> </div> </tem ...

Implementing a 1-second delay in a Vue.js delete request

I have items that are retrieved through API calls and users can add them to their cart. They also have the option to delete items from the cart, but I want the item to be visually removed from the front-end after 1 second because of an animation on the del ...

Angular AutoComplete feature does not accurately filter the list items

I need to implement an auto-complete feature for the county field due to a large number of items in the list causing inconvenience to users who have to scroll extensively. Currently, there are two issues with the code. The first problem is that although t ...

Utilizing Color with Nuxt and Vuetify: Enhancing Components such as v-toolbar

Hello, I need help with my Nuxt 2 and Vuetify 2 project. I want to customize a simple Vuetify v-toolbar component by giving it a specific color. The official documentation suggests using the following code: <template> <v-toolbar flat color=&q ...

Rollup ESM creates faulty imports

I need to package a TypeScript React app as a component in an ES module or UMD, but the ES bundle generated is producing an invalid JS module. When bundling, I receive the following hints. However, I am unable to find a solution for this. (!) Missing glob ...

React Date-Picker is unable to process a date input

Recently, I've been working on integrating a date picker into my application. I came across this helpful library that provides a date picker component: https://www.npmjs.com/package/react-date-picker So far, I have set up the component in the follow ...

What are the steps to save information to Firebase's Realtime Database?

Currently, I am facing an issue where user location data is not being written into our Firebase Realtime Database even though the console confirms that the data is fetched correctly every 2 seconds. I am seeking assistance on how to resolve this problem. ...