【发布时间】:2019-10-28 04:28:17
【问题描述】:
我需要在 Vue JS 中为单个文件组件编写单元测试。我的项目基于Vue Cli,为了测试,我选择了 Mocha/Chai 组合。
我的组件在挂载之前使用 Axios 从 URL 加载一些 JSON。在这个阶段,我不想在测试期间模拟这个负载,我只想让这个请求失败,然后显示一些信息。
非常我的组件 Async.vue 的简化示例:
<template>
<div>
<h1>Async Request test</h1>
<b v-if="finished">Request finished</b>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
import axios from "axios";
@Component
export default class AsyncRequest extends Vue {
finished = false;
beforeMount() {
axios.get("not/real/url").then((response) => {
this.finished = true;
},
(error) => {
this.finished = true;
});
}
}
</script>`
这是我的测试脚本:
import { expect } from "chai";
import { shallowMount } from "@vue/test-utils";
import Async from "@/components/Async.vue";
describe("Async.vue", () => {
it("Renders 'Request finished'", (done) => {
const wrapper = shallowMount(Async, {});
wrapper.vm.$nextTick(() => {
expect(wrapper.text()).to.include("test"); // it passes
expect(wrapper.text()).to.include("finished"); // it fails
done();
});
});
});
我希望我的测试能够通过。 我只需要在 beforeMount 完成后测试我的组件。 让我再次强调一下 - 我现在不想从 axios.get 获取真实或模拟的数据。
【问题讨论】:
-
您仍然需要模拟
GET请求。你只需要嘲笑失败而不是成功。 -
我已经安装了github.com/axios/moxios 并模拟了请求。好消息:模拟正在工作,因为我的组件获取了 moxios 返回的数据。坏消息:测试仍然失败,因为
wrapper.text()显然是在请求完成之前测试的。
标签: unit-testing vuejs2 mocha.js vue-component