Test fails : Jest + Vue 3 + Vuex + Typescript : TypeError: Cannot read property 'then' of undefined
Test fails : Jest + Vue 3 + Vuex + Typescript : TypeError: Cannot read property 'then' of undefined
我有一个我们将称为 Form.vue 的组件,它有一个按钮,可以触发该组件的方法,我在其中执行存储操作。
我想在调度后链接一个 .then() 函数,但是当我重新运行测试时,它现在失败并显示此消息:错误:未捕获 [TypeError:无法读取 属性 'then'未定义]
如果我简单地注释 .then() 块,测试将通过:
->你知道如何解决这个问题吗?
Form.vue
<script lang="ts">
import { defineComponent } from "vue";
import { AxiosResponse } from "axios";
export default defineComponent({
name: "Form",
props: ["FormAnswers"],
data(): {
localFormAnswers: FormAnswersType;
} {
return {
localFormAnswers: { ...this.FormAnswers },
};
},
methods: {
saveFormAnswers() {
this.$store
.dispatch("addFormAnswers", this.localFormAnswers)
.then((response: AxiosResponse) => {
some function there
}
}
});
},
store.ts
addFormAnswers(
context: Context,
formAnswer: FormAnswersType
): Promise<void> {
return HTTP.post("/form-answers/", formAnswer);
}
Form.spec.ts
describe("Form Answers component", () => {
it("triggers saveFormAnswers method, when button is clicked", async () => {
const $store = {
dispatch: jest.fn(),
};
const wrapper = shallowMount(FormAnswers, {
global: {
mocks: {
$store,
},
},
});
const spy = jest.spyOn(wrapper.vm, "saveFormAnswers");
await wrapper.find("button").trigger("click");
expect(spy).toHaveBeenCalledTimes(1);
});
你在嘲笑 $store
错了。您提供的函数返回 void
而不是 returns 和 Promise
.
的函数
试试这个
const $store = {
dispatch: () => new Promise((resolve) => resolve()),
};
我有一个我们将称为 Form.vue 的组件,它有一个按钮,可以触发该组件的方法,我在其中执行存储操作。
我想在调度后链接一个 .then() 函数,但是当我重新运行测试时,它现在失败并显示此消息:错误:未捕获 [TypeError:无法读取 属性 'then'未定义]
如果我简单地注释 .then() 块,测试将通过:
->你知道如何解决这个问题吗?
Form.vue
<script lang="ts">
import { defineComponent } from "vue";
import { AxiosResponse } from "axios";
export default defineComponent({
name: "Form",
props: ["FormAnswers"],
data(): {
localFormAnswers: FormAnswersType;
} {
return {
localFormAnswers: { ...this.FormAnswers },
};
},
methods: {
saveFormAnswers() {
this.$store
.dispatch("addFormAnswers", this.localFormAnswers)
.then((response: AxiosResponse) => {
some function there
}
}
});
},
store.ts
addFormAnswers(
context: Context,
formAnswer: FormAnswersType
): Promise<void> {
return HTTP.post("/form-answers/", formAnswer);
}
Form.spec.ts
describe("Form Answers component", () => {
it("triggers saveFormAnswers method, when button is clicked", async () => {
const $store = {
dispatch: jest.fn(),
};
const wrapper = shallowMount(FormAnswers, {
global: {
mocks: {
$store,
},
},
});
const spy = jest.spyOn(wrapper.vm, "saveFormAnswers");
await wrapper.find("button").trigger("click");
expect(spy).toHaveBeenCalledTimes(1);
});
你在嘲笑 $store
错了。您提供的函数返回 void
而不是 returns 和 Promise
.
试试这个
const $store = {
dispatch: () => new Promise((resolve) => resolve()),
};