Cypress 跨域 cy.origin 传递对象不起作用

use*_*852 0 cross-domain cypress automation-testing

我想从一个网站跨域到另一个网站,cypress 让我可以使用 cy.origin() 函数很好地做到这一点。

我还想要的是将我所在页面的页面对象模型传递到此函数中。

我尝试了几种实例化我的类并根据文档传递到参数的方法。我无法让它在运行时执行...

const args = {
    testObject: new MyPageObject()
};

// As the domain has changed we need to use the cy.origin function
cy.origin(dfBaseURL, {
    args: {
        args
    }
}, ({
    args
}) => {

    args.testObject.getContinueButton().click({
        force: true
    });

})
Run Code Online (Sandbox Code Playgroud)

目前与...

在此输入图像描述

Sit*_*sch 6

不,我也试过这个,你做不到。

文档说

传递给 args 的值必须是可序列化的

这是我的概念证明

class MyPageObject {
  add() {
    return 1+2
  }
}

it('function serialization with cy.origin', () => {

  const testObject = new MyPageObject()
  
  console.log(typeof testObject.add)         // yields "function"
  console.log(JSON.stringify(testObject))    // yields "{}" - add() has been removed

  cy.origin('https://example.com', { args: { testObject } }, ({testObject}) => {

    console.log(testObject, testObject.add)  // yields "{}" and "undefined"

  })
})
Run Code Online (Sandbox Code Playgroud)

从技术上讲,您可以预序列化对象并覆盖函数属性的默认序列化行为(将它们转换为字符串,如您在开发工具中看到的那样),然后使用可怕的“eval”来重新实例cy.origin()化所有方法。

但不,基本上页面对象不太适合 Cypress 范例。


使用 JSON 或对象代替

正如注释中所建议的,可以使用一个简单的对象来传递选择器。

const selectors = requires('selectors.json')

/* 
 Selectors is an object with string properties, it is serializable
 {
   login: 'input#user-name',
   ...
*/

it('object map of selectors with cy.origin', () => {
  
  console.log(typeof selectors.login)        // yields "string"
  console.log(JSON.stringify(selectors))     // yields "{login: ...}" 

  cy.origin('https://example.com', { args: {selectors} }, ({selectors}) => {

    console.log(JSON.stringify(selectors))   // yields "{login: ...}" 

  })
})
Run Code Online (Sandbox Code Playgroud)