【发布时间】:2021-09-27 11:45:44
【问题描述】:
我遇到了一个奇怪的情况,不知道为什么。基本上在我的 HTML 中,如果我渲染“actor [0]”,测试运行良好,控制台日志显示 setData 中存在的整个“actor”对象
但是,如果我尝试访问“actor”对象的属性,例如 actor[0].firstname,测试会抛出 TypeError-can't-read-property-of-undefined。
奇怪的部分是控制台日志记录“wrapper.vm.actor[0].firstname”工作正常,所以它看起来不像是一个异步问题。
myapps.spec.js
import { mount } from "@vue/test-utils";
import MyApps from "@/pages/myapps.vue";
import Vuetify from "vuetify";
describe("Testing Myapps", () => {
let vuetify;
beforeEach(() => {
vuetify = new Vuetify();
});
it("Checks SideBarComponent is rendered", async () => {
const wrapper = mount(MyApps, {
// localVue,
vuetify,
mocks: {
$vuetify: { breakpoint: {} }
},
stubs: {
SideBarComponent: true,
FooterComponent: true
}
});
await wrapper.setData({
actor: [
{
firstname: "bob",
lastname: "bob",
group: "actors"
}
]
});
console.log(wrapper.html()); // TypeError: Cannot read property 'first name' of undefined
console.log(wrapper.vm.actor[0].firstname); // "bob" if I set the template back to actor[0] so the test runs
});
});
myapps.vue
<template>
<div>
<v-app>
<v-col cols="3">
<v-btn
text
@click="getAcceptedApplications"
elevation="0"
block
>Accepted {{actor[0].firstname}}</v-btn>
</v-col>
</v-app>
</div>
</template>
<script>
export default {
async asyncData({ params, $axios, store }) {
try {
const body = store.getters.loggedInUser.id;
const [applications, actor] = await Promise.all([
$axios.$get(`/api/v1/apps/`, {
params: {
user: body
}
}),
$axios.$get(`/api/v1/actors/`, {
params: {
user: body
}
})
]);
return { applications, actor };
if (applications.length == 0) {
const hasApps = false;
}
} catch (error) {
if (error.response.status === 403) {
const hasPermission = false;
console.log(hasPermission, "perm");
console.error(error);
return { hasPermission };
}
}
},
data() {
return {
actor: []
};
}
};
</script>
【问题讨论】:
-
你能提供你的组件的代码吗?
-
@Eduardo 嗨,是的,我已经使用本地数据存储对其进行了更新。组件还有更多内容,但这是模板中唯一使用“actor”变量的部分。
-
奇怪,我检查了代码,似乎一切正常。
actor数组实际上是如何在组件中设置的?你没有包含那部分代码。 -
在 asyncData 中进行初始 Axios 调用时,组件本身设置了“actor”。我现在添加了那部分。以这种方式设置时效果很好,所以我认为这与 setData() 在测试中的工作方式有关。
标签: vuejs2 jestjs vue-test-utils