javascript - 使用 Vue 和 Jest/Vue 测试工具模拟 API 调用

标签 javascript vue.js jestjs axios

我使用 Vue 作为前端,使用 Python/Django 作为后端。我想编写测试来确保对后端的 API 调用按预期工作,但我在模拟 Axios 调用时遇到了困难。

我可能设置错误,但你可以看到我有一个函数,该函数应该在组件“created”钩子(Hook)内部调用。因此,当创建组件时,此函数会调用我的后端,以根据 URL 附带的查询参数检索信息。这一切都有效,但我想学习如何模拟此 API 请求以编写更好的测试。

API 服务这在整个应用程序中用于调用后端。

文件路径:src/api/api.js

import axios from "axios";
import { djangoServiceUser } from "../../config.js";

export default axios.create({
  baseURL: "/api",
  timeout: 5000,
  headers: {
    "Content-Type": "application/json",
    Authorization: `Token ${djangoServiceUser}`
  }
});

单个文件组件

这确实有效:

<script>
import api from "@/api/api";

export default {
  data() {
    return {
      loading: false,
      userBusinessOptions: null
    };
  },
  methods: {
    fetchBusinesses(fwt_user_id) {
      this.loading = true;

      api.get(`companies/${fwt_user_id}`).then(
        response => {
          this.loading = false;
          let businessNames = [];
          for (let i in response.data) {
            businessNames.push(response.data[i].name);
          }
          this.userBusinessOptions = businessNames;
        },
        error => {
          this.loading = false;
        }
      );
    }
  },
  created() {
    this.fetchBusinesses(this.$route.query.fwt_user_id);
  }
};
</script>

beginApplicationVueTest.test.js 文件路径:src/views/tests/beginApplicationVueTest.test.js

import { shallowMount } from "@vue/test-utils";
import BeginApplication from "@/views/BeginApplication.vue";
import Vuetify from "vuetify";
import Vue from "vue";
import api from "@/api/__mocks__/api";

Vue.use(Vuetify);

it("fetches businessses", () => {
  const $route = {
    query: { fwt_user_id: 35 }
  };
  const wrapper = shallowMount(BeginApplication, {
    mocks: {
      $route
    }
  });
  expect(wrapper.vm.$route.query.fwt_user_id).toBe(35);

  wrapper.vm.fetchBusinesses(wrapper.vm.$route.query.fwt_user_id);
  wrapper.vm.$nextTick(() => {
    expect(wrapper.vm.userBusinessOptions).toBe("test");
    done();
  });
});

尝试模拟 API? 文件路径:src/api/mocks/api.js

假设business_list.json是来自API的示例JSON响应。

[
  {
    "id": 90,
    "user": 67
  },
  {
    "id": 89,
    "user": 67
  }
]
import businessList from "./data/business_list.json";

export default {
  get: () => Promise.resolve({ data: businessList })
};

最佳答案

您可以使用Moxios轻松模拟 Axios http 调用。对于您的用例,您可以执行以下操作:

import moxios from 'moxios'; // you have to npm install moxios
import api from './path/to/api.js';
import businessList from './path/to/business_list.json';

it('...', () => {
  // Install the axios instance the api module is exporting
  moxios.install(api);

  moxios.stubRequest(new RegExp('.*?/api/comapines.*'), {
    status: 200,
    response: { data: businessList }
  });


  // Test body...
  // Any axios call to an endpiont that matches the regExp would always return the response specified

  moxios.uninstall();
})

关于javascript - 使用 Vue 和 Jest/Vue 测试工具模拟 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58805248/

相关文章:

javascript - 如何在3个按钮后显示 "read more"链接

javascript - 纯 Javascript slider

javascript - Angular2 - 共享组件 Controller

vue.js - 使用 v-if 包裹元素,否则只有内容本身

regex - 创建 React App 找不到测试

javascript - 为什么设置 iframe 的 allowfullscreen 属性似乎没有保留该属性

javascript - 在 javascript/vue 中按名称对国家/地区进行排序

javascript - 数据变化随机更新 - Vue/Vuex

javascript - 使用 Jest 时如何模拟模块

javascript - 如何在测试之间重置 redux-test-utils 存储