6

我的单元测试有一个有趣的问题。我的单元测试是为了单击组件内的按钮而编写的。这个按钮调用一个组件方法,该方法包含一个类的实例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()
    })
})
4

2 回答 2

4

我想到了。显然,如果有问题的方法是用参数调用的,Jest.toHaveBeenCalled()不会返回 true。你必须使用.toHaveBeenCalledWith(). 我在他们的文档中没有看到任何关于此警告的内容,但似乎确实如此。

这是我通过的测试代码

it('should resend email hash', async () => {
    const email = 'testemail@test.com'
    const wrapper = mount(AccountManagementForgottenPasswordSubmitted, {
        localVue,
        computed: {
            userEmail() {
                return email
            },
        },
    })

    await wrapper.find('button').trigger('click')
    expect(Service.requestPasswordReset).toHaveBeenCalledWith({
        email: email
    })
})
于 2018-08-20T16:05:42.140 回答
0

您可以使用inject-loader来模拟您的服务

基本思路:

const RecoveryEmailSentInjector = require('!!vue-loader?inject!./AccountManagement.RecoveryEmailSent')
import Service from '@/someDir/Service'

const mockedServices = {
  '@/someDir/Service': Service
}

describe('Recovery Email Sent', () => {

    it('should resend recovery email', async () => {
      const RecoveryEmailSentWithMocks = RecoveryEmailSentInjector(mockedServices)

      const wrapper = mount(RecoveryEmailSentWithMocks, { 
        ...
      })
      await wrapper.find('button').trigger('click')
      expect(mockMethods.resend).toHaveBeenCalled()
      expect(mockedServices.requestPasswordReset).toHaveBeenCalled()
    })
})
于 2018-08-18T02:54:03.320 回答