我的单元测试有一个有趣的问题。我的单元测试是为了单击组件内的按钮而编写的。这个按钮调用一个组件方法,该方法包含一个类的实例Service
(axios 的包装类)。这个组件方法唯一做的就是调用Service.requestPasswordReset()
. 我的单元测试需要验证是否Service.requestPasswordReset
被调用。
我知道我正确地模拟了我的服务类,因为这通过了我的单元测试:
await Service.requestPasswordReset()
expect(Service.requestPasswordReset).toHaveBeenCalled()
而且我知道我在单击时正确调用了该方法,因为这通过了我的单元测试:
await wrapper.find('button').trigger('click')
expect(mockMethods.resend).toHaveBeenCalled()
我只是无法让我的测试注册该Service
方法被调用。有任何想法吗?
零件
<template lang="pug">
Layout
section
header( class="text-center py-4 pb-12")
h1( class="text-grey-boulder font-light mb-4") Recovery Email
p( class="text-orange-yellow") A recovery email has been sent to your email address
div( class="text-center")
div( class="mb-6")
button(
type="button"
@click.stop="resend()"
class="bg-orange-coral font-bold text-white py-3 px-8 rounded-full w-48"
) Resend Email
</template>
<script>
import Layout from '@/layouts/MyLayout'
import Service from '@/someDir/Service'
export default {
name: 'RecoveryEmailSent',
page: {
title: 'Recovery Email Sent',
},
components: {
Layout,
},
data() {
return {
errorMessage: null
}
},
computed: {
userEmail() {
const reg = this.$store.getters['registration']
return reg ? reg.email : null
},
},
methods: {
async resend() {
try {
await Service.requestPasswordReset({
email: this.userEmail,
})
} catch (error) {
this.errorMessage = error
}
},
},
}
</script>
服务.js
import client from '@/clientDir/BaseClient'
class Service {
constructor() {
this.client = client(baseUrl)
}
requestPasswordReset(request) {
return this.client.post('/account_management/request_password_reset', request)
}
}
export { Service }
export default new Service()
Service.js 中__mock__
export default {
requestPasswordReset: jest.fn(request => {
return new Promise((resolve, reject) =>
resolve({
data: {
statusCode: 'Success',
},
})
)
})
}
单元测试
jest.mock('@/someDir/Service')
import { shallowMount, mount, createLocalVue } from '@vue/test-utils'
import RecoveryEmailSent from './AccountManagement.RecoveryEmailSent'
import Service from '@/someDir/Service'
const localVue = createLocalVue()
// localVue.use(Service) // <-- Tried this, didn't work
describe('Recovery Email Sent', () => {
it('should resend recovery email', async () => {
const mockMethods = {
resend: jest.fn()
}
const email = 'testemail@test.com'
const wrapper = mount(RecoveryEmailSent, {
localVue,
computed: {
userEmail() {
return email
},
},
methods: mockMethods
})
// await Service.requestPasswordReset()
await wrapper.find('button').trigger('click')
expect(mockMethods.resend).toHaveBeenCalled()
expect(Service.requestPasswordReset).toHaveBeenCalled()
})
})