[Vue warn]: Error in v-on handler (Promise/async): "TypeError: Cannot read property 'get' of undefined" vue test util
[Vue warn]: Error in v-on handler (Promise/async): "TypeError: Cannot read property 'get' of undefined" vue test util
我正在尝试像这样在 nuxt.js
中模拟一个 axios
put 请求:
组件方法(Composition API approach):
const doSomething = async (): Promise<void> => {
const token = $cookies.get("token");
const headers = {
Authorization: `Bearer ${token}`,
};
try {
const response = await $axios.$put(
`/api/v1/post/${data.value.id}/update`,
{
status: "ok",
},
{ headers }
);
} catch (err) {
console.log(err);
}
};
和测试文件:
import { shallowMount } from "@vue/test-utils";
import axios from "axios";
import MyComponent from "~/components/MyComponent/index.vue";
const mockedAxios = axios as jest.Mocked<typeof axios>
const mockRes = { code: 200 };
jest.mock("axios", () => ({
put: jest.fn(() => {
mockRes;
}),
}));
describe("MyComponent.vue", () => {
const wrapper = shallowMount(MyComponent);
test("should do something", async () => {
await wrapper.find('[data-test="do-something"]').trigger("click");
});
});
如您所见,一切看起来都很好,但是当我 运行 测试时,控制台出现一些错误
例如,此时我收到此错误:
[Vue warn]: Error in v-on handler (Promise/async): "TypeError: Cannot read property 'get' of undefined"
我认为是 $cookies.get
但为什么会这样呢?我该如何解决?
您可以像这样模拟 $cookies
:
const wrapper = shallowMount(MyComponent, {
mocks: {
$cookies: {
get: jest.fn()
}
}
});
我正在尝试像这样在 nuxt.js
中模拟一个 axios
put 请求:
组件方法(Composition API approach):
const doSomething = async (): Promise<void> => {
const token = $cookies.get("token");
const headers = {
Authorization: `Bearer ${token}`,
};
try {
const response = await $axios.$put(
`/api/v1/post/${data.value.id}/update`,
{
status: "ok",
},
{ headers }
);
} catch (err) {
console.log(err);
}
};
和测试文件:
import { shallowMount } from "@vue/test-utils";
import axios from "axios";
import MyComponent from "~/components/MyComponent/index.vue";
const mockedAxios = axios as jest.Mocked<typeof axios>
const mockRes = { code: 200 };
jest.mock("axios", () => ({
put: jest.fn(() => {
mockRes;
}),
}));
describe("MyComponent.vue", () => {
const wrapper = shallowMount(MyComponent);
test("should do something", async () => {
await wrapper.find('[data-test="do-something"]').trigger("click");
});
});
如您所见,一切看起来都很好,但是当我 运行 测试时,控制台出现一些错误 例如,此时我收到此错误:
[Vue warn]: Error in v-on handler (Promise/async): "TypeError: Cannot read property 'get' of undefined"
我认为是 $cookies.get
但为什么会这样呢?我该如何解决?
您可以像这样模拟 $cookies
:
const wrapper = shallowMount(MyComponent, {
mocks: {
$cookies: {
get: jest.fn()
}
}
});