Vue Test Utils(Mocha,Chai)-如何等待HTTP请求

时间:2019-06-13 14:32:34

标签: unit-testing vuejs2 mocha vue-component

我需要在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获取真实或模拟的数据。

1 个答案:

答案 0 :(得分:0)

感谢Stephen Thomas评论,我被带到了正确的道路。

必须满足两个条件:

  1. 必须模拟请求(我使用过https://github.com/axios/moxios/)。
  2. Flush-promises必须使用。

请参阅以下改进的测试代码:

import moxios from "moxios";
import { expect } from "chai";
import { shallowMount } from "@vue/test-utils";
import flushPromises from "flush-promises";
import Async from "@/components/Async.vue";

describe("Async.vue", () => {
  it("Renders 'Request finished'", async () => {
    moxios.install();
    moxios.stubRequest(/.*/, {
      status: 200,
      responseText: "hello guy",
    });

    const wrapper = shallowMount(Async, {});
    await flushPromises();

    expect(wrapper.text()).to.include("finished"); // it passes now
  });
});