使用Cypress访问VueJS中的数据模型(应用程序操作) [英] Access data model in VueJS with Cypress (application actions)

查看:42
本文介绍了使用Cypress访问VueJS中的数据模型(应用程序操作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了此博客文章:

I recently came across this blog post: Stop using Page Objects and Start using App Actions. It describes an approach where the application exposes its model so that Cypress can access it in order to setup certain states for testing.

链接中的示例代码:

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

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

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

I'd like to try this approach in my VueJS application but I'm struggling with how to expose "the model".

我知道可以公开Vuex商店,如下所述:

I'm aware that it's possible to expose the Vuex store as described here: Exposing vuex store to Cypress but I'd need access to the component's data().

那么,我该如何公开 HelloWorld.data.message 是否可以从赛普拉斯访问?

So, how could I expose e.g. HelloWorld.data.message for being accessible from Cypress?

codesandbox.io上的演示应用程序

是否可以通过选项/数据API ?

推荐答案

Vue非常擅长为插件等提供内部信息.只需 console.log()即可发现数据所在的位置运行时.

Vue is pretty good at providing it's internals for plugins, etc. Just console.log() to discover where the data sits at runtime.

例如,要 读取 内部Vue数据,

For example, to read internal Vue data,

app 级别(main.js)

either from the app level (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()来保持可观察性

But actions in the referenced article implies setting data, and in Vue that means you should use Vue.set() to maintain observability.

由于Vue在 this.$ root 上公开,

cy.window().then(win => {
  const component = win.HelloWorld;
  const Vue = component.$root;
  Vue.$set(component, 'message', newValue);
}


P.S.在v3中,使用 Vue.set()的需求可能会消失,因为它们正在通过代理实现可观察性-您也许可以分配该值.


P.S. The need to use Vue.set() may go away in v3, since they are implementing observability via proxies - you may just be able to assign the value.

您可以在已安装的挂钩中的Vue组件中显示二传手

You could expose a setter within the Vue component in the mounted hook

mounted() {
  this.$root.setHelloWorldMessage = this.setMessage;
},
methods: {
  setMessage: function (newValue) {
    this.message = newValue;
  }
}

但是现在我们正在考虑一种情况,其中赛普拉斯测试看起来像是应用程序的另一个组件,需要访问HelloWorld的状态.

But now we are looking at a situation where the Cypress test is looking like another component of the app that needs access to state of the HelloWorld.

在这种情况下,您引用的Vuex方法似乎是处理问题的更简洁的方法.

In this case the Vuex approach you referenced seems the cleaner way to handle things.

这篇关于使用Cypress访问VueJS中的数据模型(应用程序操作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆