【问题标题】:How to test Vue3 and intertia with jest如何用玩笑测试 Vue 3 和惯性
【发布时间】:2021-12-23 10:15:31
【问题描述】:

在使用Laravel Mix 设置的Laravel + Vue3 + Inertia 项目中,我们如何创建前端测试?

特别是,我不知道如何处理InertiaShare DatausePage()useForm 方法?

我面临的第一个错误是:

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

【问题讨论】:

    标签: laravel jestjs vuejs3 vue-test-utils inertiajs


    【解决方案1】:

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

    密钥在Jest Partial Mocking
    您可以使用 Jest Partial Mocking 模拟 useFormusePageShared Data
    设置vue-test-util 后,我创建了这个测试文件,它的工作就像一个魅力。

    在下面的示例中,i18n 使用vue-test-utilsconfig 对象进行模拟。 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.')
    })
    

    【讨论】:

      猜你喜欢
      • 2020-02-06
      • 2020-06-30
      • 2020-06-29
      • 1970-01-01
      • 2021-02-10
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多