【发布时间】:2020-04-29 08:55:35
【问题描述】:
我是单元测试的新手,我想用一个方法测试一个组件,该方法内部我使用this.random 函数和带有 Jest 的 jQuery。
我想测试是否调用了openPost方法?
当我进行测试时,它会抛出错误 this.$ is not a function 和 this.random is not a function。
如何编写测试?
组件:
<template>
<div @click="openPost('note')" class="ml-3 text-center pointer noteBtn">
<i class="fal color-9e fa-handshake"></i>
<div class=" fs-14 color-50">metting</div>
</div>
</template>
export default {
data() {
return {
addNewKey: '',
addNewType: '',
showModal: false,
showNegoModal: false,
data: {}
}
},
methods: {
openPost(type, data) {
this.addNewType = type
if (data) this.data = data
else this.data = {}
this.addNewKey = this.random()
this.$nextTick(() => {
if (type === 'call') {
this.$('#createContact').modal('show')
} else if (type === 'note') {
this.$('#createNote').modal('show')
} else if (type === 'negotiation') {
if (data) {
this.showNegoModal = true
this.$nextTick(() => {
this.$('#CompanyNegoModal2').modal('show')
})
} else this.createnegopopup.show = true
}
})
}
}
测试:
import { shallowMount } from '@vue/test-utils'
import component from '../../components/component'
global.Math.random = jest.fn()
global.$ = jest.fn()
describe('AddDetailToCompany', () => {
let wrapper = null
beforeEach(() => {
wrapper = shallowMount(component)
})
afterEach(() => {
wrapper.destroy()
jest.clearAllMocks()
})
test('calls openPost when noteBtn is clicked', () => {
const openPost = jest.fn()
wrapper.find('.noteBtn').trigger('click')
expect(openPost).toHaveBeenCalledWith('note')
wrapper.vm.$nextTick().then(function() {
expect(global.Math.random).toHaveBeenCalled()
expect(global.$).toHaveBeenCalledWith('#createNote')
})
})
})
【问题讨论】:
标签: unit-testing vue.js jestjs