【问题标题】:Vue Test Utils (Mocha, Chai) - how to wait for http requestVue Test Utils (Mocha, Chai) - 如何等待 http 请求
【发布时间】: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


【解决方案1】:

感谢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
  });
});

【讨论】:

  • 为什么请求被mock了?
猜你喜欢
  • 1970-01-01
  • 2016-06-04
  • 2022-10-16
  • 1970-01-01
  • 2019-04-17
  • 2020-07-28
  • 1970-01-01
  • 2017-07-30
  • 1970-01-01
相关资源
最近更新 更多