首页 > 解决方案 > 如何在依赖外部依赖的 vue.js 中对组件进行单元测试?

问题描述

我正在尝试编写一个单元测试(带有笑话),它断言数据正在被推送到 job_execs 中。我遇到的两个问题是模拟 api 端点,以及是否可以this.$route.params.tool在单元测试中模拟。

所以主要问题是,我可以用下面的组件写一个测试吗?我知道应该可以模拟 api 端点(仍然没有弄清楚如何),但我担心我的组件中有太多的外部依赖项,以至于无法进行单元测试。我是否需要重写我的组件以支持单元测试?

乔布斯.vue

<script>
export default {
  name: "Jobs",
  data() {
    return {
      job_execs: []
    }
  },
  created() {
    this.JobExecEndpoint = process.env.VUE_APP_UATU_URL + '/api/v1/job_execution/?tool='+this.$route.params.tool+'&job='+this.$route.params.job+'&id='+this.$route.params.id
    fetch(this.JobExecEndpoint)
    .then(response => response.json())
    .then(body => {
      this.job_execs.push({
        'code_checkouts': body[0].code_checkouts,
      })
    })
    .catch( err => {
      console.log('Error Fetching:', this.JobExecEndpoint, err);
      return { 'failure': this.JobExecEndpoint, 'reason': err };
    })
  },
};
</script>

单元测试

import { shallowMount } from "@vue/test-utils";
import fetchMock from 'fetch-mock'
import flushPromises from 'flush-promises'
import Jobs from "../../src/components/execution_details/Jobs.vue";

const job_execs = [
{
'code_checkouts': [{'name': 'test', 'git_hash': 'test', 'git_repo': 'test'}, {'name': 'test', 'git_hash': 'test', 'git_repo': 'test'}]}]
const $route = {
  params = {
  tool: 'jenkins',
  job: 'jobname',
  id: '1',
  }
}

describe('Jobs.vue', () => {
  beforeEach(() => {
    fetchMock.get(process.env.VUE_APP_UATU_URL + '/api/v2/job_execution/?product=eBay%20Mobile&tool='+$route.params.tool+'&job='+$route.params.job+'&id='+$route.params.id, job_execs)
  })

  it('Construct a JSON object of Git Refs from job_execution API', async () => {
    const wrapper = shallowMount(GitRefs)
    await flushPromises()

    expect(wrapper.vm.job_execs).toEqual(job_execs)
  })

  afterEach(() => {
    fetchMock.restore()
  })
})

标签: javascriptunit-testingvue.js

解决方案


您需要导入组件中使用的所有依赖项,还需要导入使用路由器、axios 等的任何全局值或属性


推荐阅读