TypeError: Unable to require `.d.ts` file

1k Views Asked by At

Stack

  • vue 3.2.19
  • @vue/test-utils 2.0.0-rc.15
  • typescript 4.1.6

Problem

I have a problem when running the command vue-cli-service test:unit --no-cache.

Please check TypeError

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

Occurs when used in the Vue component imported typescript file from the node modules in which in turn there is another typescript file import

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()}`
    );
  });
});

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>

fake-util.ts

import { Helpers } from "./helpers";

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

helpers.ts

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

Full example https://github.com/baronkoko/vue-unit-tests-type-error

Possible solutions:

  1. Add the extension to the imported file, but it will look like this

    // @ts-ignore

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

  2. Enable isolatedModules to the jest.config.js ts-jest

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

But then we get a lot of SyntaxError, for example, if there is optional chaining SyntaxError

Can anyone help with this, please?

1

There are 1 best solutions below

0
On

Solved this problem by having all external modules built with a Rollup in esm format and using them instead