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

Vue Test Utils (Mocha, Chai) - how to wait for http request

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

感谢 Stephen Thomas 评论,我被引导到正确的路径。

必须满足两个条件:

  1. 请求必须被mock(我用过https://github.com/axios/moxios/)。
  2. 必须使用
  3. 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
  });
});