使用Vue和Jest / Vue测试实用程序模拟API调用

时间:2019-11-11 16:34:43

标签: javascript vue.js jestjs axios

我在前端使用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 / 测试 /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 / 模拟 /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 })
};

1 个答案:

答案 0 :(得分:2)

您可以使用Can't send buffer to gnuplot under Windows轻松模拟Axios http呼叫。对于您的用例,您可以执行以下操作:

def main():
    while True:
        type_of_user = input("Are you a student? ")
        if type_of_user.lower() == "y":
            print("Your price is $3.50/m")
            break
        elif type_of_user.lower() == "n":
            print("Your price is $5.00/m")
            break
        else:
            print("Not valid")