JavaScript >> Javascript 文檔 >  >> Vue.js

使用 Pinia 集成測試 Vue3

我正在開發一個 Vue 3 項目,我必須使用 vue test utils 為依賴於 Pinia 的組件編寫集成測試,同時需要在安裝該組件之前在 Pinia 商店上設置一些初始狀態。這導致了一個問題:

  • 在配置 Pinia 存儲之前無法安裝組件,
  • 在安裝組件之前無法配置 Pinia 存儲。在 vue test utils 官方文檔的這一段中閱讀原因。

一種解決方案是重構代碼,以便組件在安裝時不依賴存儲。但這將是太多的工作,而且對我們的代碼庫也太嚴格了。我們不應該在組件生命週期鉤子中限制對存儲的訪問!

因此,在這篇文章中提出了另一種解決方案,即在專門為集成測試設計的包裝組件中渲染組件:

IntegrationTestWrapper.vue

<script setup lang="ts">
import { useMyStore } from '@/stores/myStore'

// === setup any Pinia stores here ===
useMyStore().$patch({ foo: 'bar' })
// ======

defineProps(['component'])
</script>

<template lang="pug">
component(:is="component")
</template>

然後在我們的測試裡面我們可以寫:

MyComponent.spec.ts

import { flushPromises, mount } from '@vue/test-utils'
import { createPinia } from 'pinia'

describe('MyComponent', () => {
  it('should mount', async () => {
    const wrapper = await mount(IntegrationTestWrapper, {
      props: {
        component: 'MyComponent', 
        anotherProp: 'abc', // will be passed to child component
      },
      global: {
        plugins: [createPinia()], // initializes Pinia
        stubs: { MyComponent }
      },
    })
    await flushPromises() // make sure all promises in lifecycle hooks are resolved
    expect(wrapper.exists()).toBe(true)
    // further assertions
  })
})

現在一切都按正確的順序完成了:

  • Pinia 在 IntegrationTestWrapper 之前創建和初始化 已安裝。
  • IntegrationTestWrapper 在掛載 MyComponent 之前初始化存儲狀態 .
  • IntegrationTestWrapper 的道具 將被傳遞給 MyComponent .

備註:

  • IntegrationTestWrapper 沒有渲染插槽,因為它不會接收道具。
  • 你不能只調用 createPinia() 在配置 store state 之前,你會收到 Pinia is not initialized with app.use() 的錯誤 .它僅在測試中通過掛載選項進行初始化。

Tutorial JavaScript 教程
  1. Node.js:檢查 ESM 模塊是否為“主”模塊

  2. 如何修復 - this.setState 不是 React 中的函數錯誤

  3. 鎖定期間要學習的頂級 Vue JS 課程和教程

  4. API到底是什麼?

  5. 如何通過反應發出許多http請求

  6. 當字符串包含表情符號時刪除最後一個字符字符串

  7. Angular 的動態模塊聯合

  1. 我在 2019 年安裝的前 10 個 macOS 應用程序

  2. 必須了解委託原型的 2 個原因

  3. 5 分鐘學習 React Hooks - 初學者教程

  4. 如何在 ExpressJS 應用程序中使用 Tailwind CSS。

  5. 有沒有辦法檢查一個對像是否真的被釋放了?

  6. 學習在你的 React 項目中使用 StorybookJS

  7. 如何在jquery中獲取隨機元素?

  1. Express MySQL:使用 Express.js 和 MySQL 構建簡單的 REST API

  2. Nodejs Starter - 全棧 Vue Argon 設計

  3. 開始使用 Kendo UI 和 Vue:GIF 指南

  4. 在 Node.js 中使用 WebSocket