繁体   English   中英

如何对依赖外部依赖项的vue.js中的组件进行单元测试?

[英]how to unit test components in vue.js that rely on external dependencies?

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

因此,主要问题是,我可以使用以下组件编写测试吗? 我知道应该可以模拟api端点(仍然没有弄清楚该怎么做),但是我担心的是我在组件中有太多的外部依赖关系,因此无法进行单元测试。 我是否需要重写组件以支持单元测试?

乔布斯

<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()
  })
})

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM