[英]How to expose vuex store of nuxt app to cypress?
我想為使用 cypress 的 vuex 商店創建測試,用於使用 nuxt 構建的項目。 問題是我找不到一種方法將商店公開給 cypress,以便我可以從這樣的測試中分派動作(代碼取自這個答案):
cy.visit()
cy.window().should('have.property', '__store__')
cy.window().then( win => {
win.__store__.dispatch('myaction')
})
最接近我的問題的答案可以在這里找到。 但這似乎僅適用於沒有使用 nuxt 構建的 vue.js 應用程序的有效答案,特別是因為 Nuxt 文檔表明 nuxt 已棄用它所謂的用於實例化商店的經典模式,這是參考答案中使用的方法。
任何幫助將不勝感激。
您應該通過客戶端插件在 nuxt 中公開它:
// plugins/cypress.js
const isCypress = typeof window.Cypress !== 'undefined'
export default ({ store }) => {
if (isCypress) {
window.store = store
}
}
然后在 cypress 中你可以測試它:
// cypress/integration/example.spec.js
describe('Store', () => {
it('Application store is exposed to cypress', () => {
cy.visit('/')
cy.window().should('have.property', 'store')
})
})
該商店也可以通過 NuxtJS 助手$nuxt 訪問。 您可以通過window
在 Cypress 中訪問它:
cy.window()
.its('$nuxt')
.then((nuxt) => {
console.dir(nuxt.$store)
})
你可以在插件中做到這一點。 例如,創建一個僅客戶端插件,將商店設置為窗口
插件/exposestore.client.js
export default ({store}) => {
window.__store__ = store
}
我為此苦苦掙扎了幾天,因為我在 Cypress 和我的應用程序之間遇到了某種競爭條件。 我沒有添加插件,而是將瀏覽器檢查添加到我的layout/default.ts
文件的掛載函數中:
mounted() {
if (window.frameElement !== null && window.frameElement.id.includes('Your App')) {
window.store = this.$store;
}
},
在驗證在這種情況下有兩個窗口時還要記住:您的 Cypress 窗口和您在 Cypress 中的應用程序窗口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.