gpt4 book ai didi

vue.js - 使用 Cypress 访问 VueJS 中的数据模型(应用程序操作)

转载 作者:行者123 更新时间:2023-12-04 00:56:17 27 4
gpt4 key购买 nike

我最近看到了这篇博文:Stop using Page Objects and Start using App Actions .它描述了一种应用程序公开其模型的方法,以便 Cypress 可以访问它以设置某些状态进行测试。

链接中的示例代码:

// app.jsx code
var model = new app.TodoModel('react-todos');

if (window.Cypress) {
window.model = model
}

我想在我的 VueJS 应用程序中尝试这种方法,但我正在为如何公开“模型”而苦苦挣扎。

我知道可以按照此处所述公开 Vuex 商店: Exposing vuex store to Cypress但我需要访问组件的 data() .

那么,我怎么能暴露例如? HelloWorld.data.message可以从 Cypress 访问?

Demo application on codesandbox.io

是否可以通过 Options/Data API ?

最佳答案

Vue 非常擅长为插件等提供内部结构。只需 console.log()发现数据在运行时的位置。
例如,到 阅读 内部 Vue 数据,
来自应用 级别(main.js)

const Vue = new Vue({...
if (window.Cypress) {
window.Vue = Vue;
}
然后在测试中
cy.window().then(win => {
const message = win.Vue.$children[0].$children[0].message;
}
或来自 组件 等级
mounted() {
if (window.Cypress) {
window.HelloWorld = this;
}
}
然后在测试中
cy.window().then(win => {
const message = win.HelloWorld.message;
}
但引用文章中的操作暗示 设置 数据,在 Vue 中这意味着你应该使用 Vue.set()以保持可观察性。
由于 Vue 在 this.$root 上公开,
cy.window().then(win => {
const component = win.HelloWorld;
const Vue = component.$root;
Vue.$set(component, 'message', newValue);
}

附言需要使用 Vue.set()可能会在 v3 中消失,因为它们正在通过代理实现可观察性 - 您可能只能分配值。

Vue HelloWorld 组件的实验性应用操作。
您可以在已安装的 Hook 中公开 Vue 组件中的 setter
mounted() {
this.$root.setHelloWorldMessage = this.setMessage;
},
methods: {
setMessage: function (newValue) {
this.message = newValue;
}
}
但是现在我们正在研究一种情况,即 Cypress 测试看起来像是应用程序的另一个组件,需要访问 HelloWorld 的状态。
在这种情况下,您引用的 Vuex 方法似乎是更简洁的处理方式。

关于vue.js - 使用 Cypress 访问 VueJS 中的数据模型(应用程序操作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62297240/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com