【问题标题】:how to unit test components in vue.js that rely on external dependencies?如何对依赖外部依赖项的 vue.js 中的组件进行单元测试?
【发布时间】:2019-06-27 22:51:12
【问题描述】:

我正在尝试编写一个单元测试(带有笑话),它断言数据正在被推送到 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()
  })
})

【问题讨论】:

    标签: javascript unit-testing vue.js


    【解决方案1】:

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

    【讨论】:

    • 当你说导入它们时,是指在单元测试中定义它们吗?
    猜你喜欢
    • 2014-05-29
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多