首页 > 解决方案 > TypeError:无法要求`.d.ts`文件

问题描述

问题

运行命令时出现问题vue-cli-service test:unit --no-cache

请检查类型错误

(链接到 CI https://github.com/baronkoko/vue-unit-tests-type-error/runs/3728921894?check_suite_focus=true

在 Vue 组件中使用时发生,从节点模块导入 typescript 文件,其中又存在另一个 typescript 文件导入

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

你好世界.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)}`;
  }
}

助手.ts

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

完整示例https://github.com/baronkoko/vue-unit-tests-type-error

可能的解决方案:

  1. 将扩展名添加到导入的文件中,但它看起来像这样

    // @ts-忽略

    从“./helpers.ts”导入{ Helpers };

  2. 为 jest.config.js ts-jest 启用 isolatedModules

    全局变量:{“ts-jest”:{ isolatedModules: true, }, },

但是随后我们会得到很多 SyntaxError,例如,如果存在可选链接SyntaxError

请问有人可以帮忙吗?

标签: typescriptvue.jsvue-test-utilsts-jestvue-jest

解决方案


通过使用 Rollupesm格式构建所有外部模块并使用它们来解决此问题


推荐阅读