Vue Test Utils / Jest-如何测试组件方法内是否调用了类方法

时间:2018-08-18 01:05:20

标签: unit-testing vue.js jestjs vuex vue-test-utils

我的单元测试有一个有趣的问题。我的单元测试被编写为单击组件内部的按钮。此按钮调用组件方法,该方法包含类Service(axios的包装器类)的实例。该组件方法唯一要做的就是调用Service.requestPasswordReset()。我的单元测试需要验证是否调用了Service.requestPasswordReset

我知道我在正确模拟我的Service类,因为这通过了我的单元测试:

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>

Service.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()

__mock__中的Service.js

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

2 个答案:

答案 0 :(得分:2)

我知道了。显然,如果所讨论的方法是通过参数调用的,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
    })
})

答案 1 :(得分:0)

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

基本思路:

>>> def f():
...   return 'True'
... 
>>> 
>>> a,b = f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack