如何用 jest 测试 Vue3 和 intertia

Kha*_*leh 1 inertiajs laravel jestjs vue-test-utils vuejs3

在一个使用Laravel++设置Vue3Inertia项目中Laravel Mix,我们如何创建前端测试?

特别是,我不知道如何处理' InertiasShare Data和方法?usePage()useForm

我面临的第一个错误是:

    TypeError: Cannot read properties of undefined (reading 'someSharedData')                                                                                          
                                                                                                                                                              
      2 |                                                                                                                                                     
      3 | export const handleSometing = (something) =>                                                                                                        
    > 4 |   usePage().props.value.someSharedData                                                                                                
        |   ^                                                                                                                                                 
      5 |     ...                                                                                                              
      6 |   )
Run Code Online (Sandbox Code Playgroud)

Kha*_*leh 5

在谷歌搜索了一些无用的时间并没有找到任何具体问题后,我找到了这个解决方案。

钥匙在Jest Partial Mocking
您可以模拟useForm, usePage, 然后Shared Data使用Jest Partial Mocking.
设置完成后vue-test-util,我创建了这个测试文件,它运行得非常顺利。

在下面的示例中,i18n使用config的对象来模拟vue-test-utils。的Inertia方法被 嘲笑jest.mock()

import { config, shallowMount } from '@vue/test-utils'
import Dashboard from '@/Components/ExampleComponent'

config.global.mocks = {
  $t: () => '',
}

jest.mock('@inertiajs/inertia-vue3', () => ({
  __esModule: true,
  ...jest.requireActual('@inertiajs/inertia-vue3'), // Keep the rest of Inertia untouched!
  useForm: () => ({
    /** Return what you need **/
    /** Don't forget to mock post, put, ... methods **/
  }),
  usePage: () => ({
    props: {
      value: {
        someSharedData: 'something',
      },
    },
  }),
}))

test('Render ExampleComponent without crash', () => {
  const wrapper = shallowMount(ExampleComponent, {
    props: {
      otherPageProps: {}
    }
  })

  expect(wrapper.text()).toContain('Hi! I am ExampleComponent.')
})
Run Code Online (Sandbox Code Playgroud)