如何在依赖外部依赖项的vue.js中测试组件



我正在尝试编写一个单位测试(带JEST(,该测试声称数据被推入Job_execs。我遇到的两个问题正在模拟API端点,如果可以在单元测试中模拟this.$route.params.tool

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

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

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

最新更新