我正在尝试测试 jest 框架中的方法。对于 javascript 方法,我能够使用 require() 函数从文件中导入方法并对其进行测试(expect(addition(1,2).toBe(3)))。 但无法在 VueJS 方法中复制相同的内容。
// VueJS
export default defineComponent({
name: "App",
components: {
HelloWorld,
},
methods: {
addition(a: number, b: number) {
return a + b;
},
subtraction(a: number, b: number) {
return a - b;
},
multiplication(a: number, b: number) {
return a * b;
},
},
});
测试文件
import addition from "./App.vue"
describe("HelloWorld.vue", () => {
it("testing vue method", () => {
expect(addition(1,2).toBe(3));
});
});
//error on line 4 states "Value of type 'DefineComponent<{}, {}, any, ComputedOptions, MethodOptions, ComponentOptionsMixin,
// ComponentOptionsMixin, ... 4 more ..., {}>' is not callable. Did you mean to include 'new'?"
答案 0 :(得分:1)
App.vue
文件编译成组件定义,用于通过 Vue Test Util 的 mount
或 shallowMount
实例化 App
组件,从而产生一个测试包装纸。包装器有一个 vm
property,可以直接访问组件的方法和道具。
所以你的测试应该类似于:
import { shallowMount } from "@vue/test-utils";
import App from "./App.vue";
describe("App.vue", () => {
it("testing vue method", () => {
const wrapper = shallowMount(App);
expect(wrapper.vm.addition(1,2)).toBe(3);
});
});