【问题标题】:Jest test on functions which are in onMounted Composition API Vue 2对 onMounted Composition API Vue 2 中的函数的开玩笑测试
【发布时间】:2021-09-12 15:38:36
【问题描述】:

谁能告诉我如何为onMounted钩子中的函数编写测试用例?我正在使用带有组合 API 插件的 vue 2。

    const getUsers = async () => {
            const usersQuery = `
                query {
                  users: {
                     id
                     username
                   }
                }
            `
            try {
                const result = await apolloClient.getGraphqlData(usersQuery)
                if (result) users.value = result.data.users
            } catch (err) {
                console.log('Error while receiving users', err)
            }
        }

下面是我的onMounted钩子

onMounted(() => {
    getUsers()
})

【问题讨论】:

    标签: vue.js jestjs vue-composition-api


    【解决方案1】:

    您不能模拟在setup() 中定义的本地函数。必须公开这些功能,以便单元测试可以访问它们。一种解决方法是在与组件相邻的外部文件中声明方法:

    // mylib.js
    export const getUsers = async () => { /*...*/ }
    

    然后将该文件导入您的组件中:

    import { onMounted } from '@vue/composition-api'
    import { getUsers } from './mylib'
    
    export default {
      setup() {
        onMounted(() => getUsers())
      }
    }
    

    然后在您的测试文件中,导入相同的文件,并使用jest.mock() 对其进行自动模拟,这样您就可以验证该函数是否在组件挂载时被调用:

    import { getUsers } from '@/components/mylib'
    import MyComponent from '@/components/MyComponent.vue'
    
    jest.mock('@/components/setupFns')
    
    describe('MyComponent', () => {
      beforeEach(() => jest.resetAllMocks())
    
      it('calls getUsers() on mount', () => {
        shallowMount(MyComponent)
        expect(getUsers).toHaveBeenCalledTimes(1)
      })
    })
    

    demo

    【讨论】:

    • 感谢您的回复。当我们在组件中有函数时,你能告诉我怎么做吗?
    • 见答案的开头。您无法在 setup 中测试本地方法,因为它们是隐藏的。
    猜你喜欢
    • 2020-02-06
    • 2020-05-29
    • 2020-03-10
    • 2020-08-24
    • 2021-08-19
    • 2019-01-04
    • 1970-01-01
    • 2017-10-20
    • 2021-09-13
    相关资源
    最近更新 更多