【问题标题】:TypeError: Unable to require `.d.ts` fileTypeError:无法要求`.d.ts`文件
【发布时间】:2021-11-20 05:28:58
【问题描述】:

堆栈

  • vue 3.2.19
  • @vue/test-utils 2.0.0-rc.15
  • 打字稿 4.1.6

问题

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

请查看TypeError

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

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

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

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

可能的解决方案:

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

    // @ts-忽略

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

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

    全局变量:{ “开玩笑”:{ 隔离模块:真, }, },

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

有人可以帮忙吗?

【问题讨论】:

    标签: typescript vue.js vue-test-utils ts-jest vue-jest


    【解决方案1】:

    通过使用 esm 格式的汇总构建所有外部模块并改用它们来解决此问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-13
      • 2020-04-30
      • 1970-01-01
      • 2021-01-13
      • 2021-02-28
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      相关资源
      最近更新 更多