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

Could there be an issue with the way I've implemented my setInterval function?

I am currently in the process of developing a stopwatch feature using React Native and implementing the setInterval function to increase a counter and update the state accordingly: Play Function (triggered upon pressing the play button) const [isRunning ...

Embed Vue applications within the container of the main Vue application

My goal is to establish a foundational Vue application that offers essential features such as signing in, navigating with a sidebar, and the flexibility to interchange navbar items. I envision creating separate Vue applications for each navbar item. Main ...

Can gRPC be integrated into Nuxt.js?

Currently, I am utilizing Nuxt.js to construct a frontend for interfacing with data obtained from a REST API. In order to interact with functions on a remote service, I am considering using gRPC as there is an endpoint available for this purpose. Despite ...

Encountering Vue Router Error while integrating Laravel 9 with Vite and Vue CLI 3

I am struggling to fix it, please assist me. I can't seem to pinpoint the issue and need some guidance. Error Image Links: https://i.stack.imgur.com/VhVXL.png https://i.stack.imgur.com/IENFm.png ...

Creating an array with varying types for the first element and remaining elements

Trying to properly define an array structure like this: type HeadItem = { type: "Head" } type RestItem = { type: "Rest" } const myArray = [{ type: "Head" }, { type: "Rest" }, { type: "Rest" }] The number of rest elements can vary, but the first element ...

What is the reason behind the lack of exported interfaces in the redux-form typings?

I've been exploring how to create custom input fields for redux-form. My journey began by examining the Material UI example found in the documentation here. const renderTextField = ({input, label, meta: { touched, error }, ...custom }) => < ...

Why does the browser indicate that a GET request has been sent but the promise does not return anything?

Having trouble with a puzzling issue and unable to find any solutions online. I am attempting to make a basic HTTP get request to receive a JSON object from an API I created (using express+CORS). I have experimented with both Axios and VueResource, yet en ...

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...

During the compilation process, Angular could not locate the exported enum

In the file models.ts, I have defined the following enum: export enum REPORTTYPE { CUSTOMER, EMPLOYEE, PROJECT } After defining it, I use this enum inside another class like so: console.log(REPORTTYPE.CUSTOMER); When I save the file, the IDE automati ...

Using custom properties from the Material-UI theme object with custom props in Emotion styled components: a step-by-step guide

I have implemented a custom object called fTokens into the MUI theme using Module augmentation in TypeScript This is how my theme.d.ts file is structured declare module "@mui/material/styles" { interface FPalette { ... } interface FTokens ...

Guide to setting data types for [key, value] pairs within a forEach iteration

I am currently encountering a typescript syntax error in my project that is indicating the need to define the prodStatus variable... const products = { 1: {isUpdating: false, qty: 2}, 2: {isUpdating: true, qty: 4} } const updatingProducts: Array< ...

A data type representing a specific category rather than a specific object

My job involves working with Sequalize models, which are essentially classes. Upon registration, these models are populated with some data that needs to be stored. To accomplish this, I store them in a list. However, when retrieving a model into a variab ...

Enhance performance in Vue.js with a translation file upgrade

If my website offers language options that change all content, where is the best place to store this information for optimal performance? Would it be more efficient to have a translation file on the client side, especially for websites with large amounts ...

What is the best way to detect the window scroll event within a VueJS component?

Looking to capture the window scroll event in my Vue component. This is what I have attempted so far: <my-component v-on:scroll="scrollFunction"> ... </my-component> I have defined the scrollFunction(event) in my component methods, but it ...

Is it possible in Typescript to determine whether an object or function was brought in through an "import * as myImport" declaration?

Currently, I am importing all exports from a file in the following way: import * as strings from "../src/string"; After that, I assign a function to a const based on a condition: const decode = (strings._decode) ? strings._decode : strings.decod ...

The split function of a string displays an undefined result

My goal is to extract all characters that come after the equal sign within a URL: let url = this.$route.query.item console.log(typeof(url)) // outputs string let status = url => url.split('=')[1] When I run the code, it shows &apo ...

Learn the art of generating multiple dynamic functions with return values and executing them concurrently

I am currently working on a project where I need to dynamically create multiple functions and run them in parallel. My starting point is an array that contains several strings, each of which will be used as input for the functions. The number of functions ...

Exploring Dynamic Component in Vue.js for Efficient Data Access

My website has a basic layout displaying search results in either table or list style. The Vue components I am using are results-array and results-list. Everything works perfectly until I switch from the first component to the second one. At that point, ...

Unexpected TypeScript issue: Unable to access the 'flags' property of an undefined entity

Upon creating a new project and running the serve command, I encountered the following error: ERROR in TypeError: Cannot read property 'flags' of undefined Node version: 12.14 NPM version: 6.13 Contents of package.json: { "name": "angular-t ...

Tips on identifying and handling errors without the need for type assertions in this code segment

My code is correct, but it's becoming difficult to maintain... interface FuncContainer<F extends (..._: Array<any>) => any> { func: F args: Parameters<F> } const func: FuncContainer<typeof Math.min> = { func: Math.min ...