Rumah  >  Soal Jawab  >  teks badan

Fungsi Vue Pinia tidak ditentukan dalam onMounted semasa menjalankan ujian unit

Saya mempunyai komponen dan kedai Pinia yang mengandungi keadaan dan beberapa operasi. Kod ini berfungsi dengan baik dalam pelayar dan ujian E2E (cypress), tetapi gagal dalam ujian unit. Saya menggunakan vue-testing-utils dan vitest.

Memanggil fungsi tersimpan daripada ujian unit berfungsi dengan baik apabila butang diklik, tetapi jika fungsi itu dipasang atau skrip utama, ujian gagal

src/components/UsersComponent.vue

<script setup>
import { onMounted } from 'vue'
import { useUsersStore } from '@/stores/users.store'

const usersStore = useUsersStore()
// usersStore.resetStatus() // <- This fails in the unit test

onMounted(() => {
  usersStore.resetStatus() // <- This fails in the unit test
})

function changeStatus() {
  usersStore.changeStatus() // <- This passes in the unit test
}
</script>

<template>
  <div>
    <p>Status: {{ usersStore.status }}</p>
    <button @click="changeStatus()">Change Status</button>
  </div>
</template>

src/stores/users.store.js

import { defineStore } from 'pinia'
import { usersAPI } from '@/gateways'

export const useUsersStore  = defineStore({
  id: 'users',
  persist: true,

  state: () => ({
    status: 'ready',
  }),

  getters: {},

  actions: {
    resetStatus() {
      this.status = 'ready'
    },
    changeStatus() {
      this.status = 'loading'
    },
  },
})

src/components/test/UsersComponent.spec.js

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { mount } from '@vue/test-utils'
import { createTestingPinia } from '@pinia/testing'

import UsersComponent from '@/components/UsersComponent.vue'
import { useUsersStore } from '@/stores/users.store'

const wrapper = mount(UsersComponent, {
  global: {
    plugins: [createTestingPinia({ createSpy: vi.fn() })],
  },
})
const usersStore = useUsersStore()

describe('UsersComponent', () => {
  it('store function is called', async () => {
    // arrange
    const spy = vi.spyOn(usersStore, 'resetStatus')
    const button = wrapper.find('button')

    // act
    await button.trigger('click')

    // assert
    expect(spy).toHaveBeenCalled()
  })
})

Ujian unit mengembalikan 2 ralat berbeza. Yang pertama ialah log konsol apabila fungsi cuba dijalankan dalam onMounted() dan yang kedua ialah apa yang dikembalikan oleh vitest.

stderr | unknown test
[Vue warn]: Unhandled error during execution of mounted hook 
  at <UsersComponent ref="VTU_COMPONENT" >
  at <VTUROOT>
FAIL  src/components/__tests__/UsersComponent.spec.js [ src/components/__tests__/UsersComponent.spec.js ]
TypeError: usersStore.resetStatus is not a function
 ❯ src/components/UsersComponent.vue:16:14
     16|
     17| <template>
     18|   <div>
       |  ^
     19|     <p>Status: {{ usersStore.status }}</p>
     20|     <button @click="changeStatus()">Change Status</button>

Saya tahu contoh ini agak asas dan tidak benar-benar memenuhi tujuan, tetapi saya ingin tahu cara menyimpan fungsi dalam onMounted() (atau tempat yang serupa) tanpa melanggar semua ujian unit saya.

P粉103739566P粉103739566323 hari yang lalu690

membalas semua(1)saya akan balas

  • P粉451614834

    P粉4516148342023-11-01 14:56:54

    Mungkin ini berguna kepada anda:

    describe('UsersComponent',  () => {
      it('changeStatus function is called', async () => {
        const wrapper = mount(UsersComponent, {
          mounted: vi.fn(), // With this you mock the onMounted
          global: {
            plugins: [createTestingPinia({
              initialState: { // Initialize the state
                users: { status: 'ready' }, 
              }
            })]
          }
        })  
      
        // Spy the method you call...
        const spy = vi.spyOn(wrapper.vm, 'changeStatus');
    
        wrapper.vm.changeStatus()
    
        expect(spy).toHaveBeenCalled()
        expect(spy).toHaveBeenCalledTimes(1)
      })
    })

    balas
    0
  • Batalbalas