javascript - 如何在依赖外部依赖的 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()
})
})
解决方案
您需要导入组件中使用的所有依赖项,还需要导入使用路由器、axios 等的任何全局值或属性
推荐阅读
- android - 导航到下一个片段时如何更改图像?
- javascript - if(item中的值)和if(item.hasOwnProperty(value))之间的javascript差异
- fabricjs - FabricJS iText 宽度和高度
- hibernate - JPQL Quesry in ManyToMany relation using JoinTable
- c# - 在负载均衡器服务器上获取 WebExceptions 标头
- spring-mvc - 如何使用 Spring MVC @RequestParam 解析不同的 ISO 日期/时间格式
- c# - 使用 using 语句正确处理 StreamWriter
- ruby-on-rails-3 - Rails 3:我有控制器名称和操作,需要为其获取路径和 http 动词
- apache-spark - 删除正在运行的 Spark JOB 的 Hive 暂存目录
- android - 如何从联系人列表中获取“ME”(所有者配置文件)配置文件数据?