【问题标题】:Mocking an API call with Vue and Jest/Vue test utils使用 Vue 和 Jest/Vue 测试工具模拟 API 调用
【发布时间】:2020-03-07 08:52:53
【问题描述】:

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

我可能设置错了,但您可以看到我有一个函数,该函数旨在在组件“已创建”钩子中调用。因此,当创建组件时,此函数会调用我的后端,以根据 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 })
};

【问题讨论】:

    标签: javascript vue.js jestjs axios


    【解决方案1】:

    您可以使用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();
    })
    

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 1970-01-01
      • 2019-04-19
      • 2018-04-29
      • 2021-03-20
      • 1970-01-01
      • 2022-07-13
      • 2018-09-01
      • 2020-03-05
      相关资源
      最近更新 更多