类型错误:无法要求".d.ts"文件



堆栈

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

问题

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

请检查TypeError

(链接到CIhttps://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()}`
);
});
});

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>

伪造的.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}/helpers。ts";;

  2. 将isolatedModules启用到jest.config.js ts jest

    全局:{"ts笑话":{isolatedModules:true,},},

但是我们得到了很多SyntaxError,例如,如果有可选的链接SyntaxError

有人能帮忙吗?

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

最新更新