我有一个方法可以获取元素hrefAppTheme的href属性,并判断它是否是字符串数组appThemes的值之一:

describe('...',() => {
    it('should ...', () => {
      (...)
      let defaultAppTheme = '';
      onMenuPage.hrefAppTheme.invoke('attr', 'href')
        .then(hrefVal => {
          if (typeof hrefVal !== 'undefined') {
            expect(hrefVal).to.be.oneOf(onMenuPage.appThemes);
            defaultAppTheme = hrefVal;

      //referencing the variable 'defaultAppTheme' further below...
    }
  });

可以肯定地认为,this.hrefAppTheme.invoke('attr', 'href')总是返回一个用户主题(一个字符串),因为上面的代码工作可靠.

因为我需要在几个不同的地方使用该逻辑,所以我想将其提取到一个方法中,并将其放入页面对象类中.这就是我所得到的:

export default class MenuPage {
  (...)
  getUserTheme(): string {
    let userTheme = '';
    cy.then(() => {
      this.hrefAppTheme.invoke('attr', 'href')
        .then(resVal => {
          if (typeof resVal !== 'undefined') {
            userTheme = resVal;
          }
        });
    });
    return userTheme;
  }

我认为我需要使用cy.wrap()方法来赋值要返回的字符串:

describe('...',() => {
    it('should ...', () => {
      (...)
      let defaultAppTheme = '';
      cy.wrap(onMenuPage.getUserTheme()).then(resVal => {
        defaultAppTheme = resVal;
        expect(defaultAppTheme).to.be.oneOf(onMenuPage.appThemes);
      });

      //referencing the variable 'defaultAppTheme' further below...

然而,这是有问题的,因为返回的值始终是空字符串,而不是解析值:

AssertionError: expected '' to be one of [ 'theme-light.css', 'theme-dark.css' ]
      + expected - actual

      +[ 'theme-light.css', 'theme-dark.css' ]

waiting for the result of an invoked attribute causes an error

如何返回Resolve-Value myWebelement.invoke('attr', 'href').then(hrefVal => {(...),以及如何通过调用此方法将其赋给变量?

或者,有没有更好的方法将工作代码提取到方法中?

推荐答案

由于Cypress命令的异步性,函数中的return会在Cypress命令设置该值之前出现.为了返回值,您必须返回获得该值的Cypress命令链.

getUserTheme(): string {
    return cy.then(() => {
      return this.hrefAppTheme.invoke('attr', 'href')
        .then(resVal => {
          return resVal ?? '';
        });
    })
  }

但是,它返回的不是string变量,而是Chainable<string>.这意味着您不必对变量使用cy.wrap(),而只需继续该链即可.

onMenuPage.getUserTheme().then(resVal => {
  expect(resVal).to.be.oneOf(onMenuPage.appThemes);
});

Node.js相关问答推荐

NX无法使用缓存运行根级脚本

聚合发布/订阅消息

EJS ForEach循环标记

使用 axios 和 Cheerio (Node js) 抓取 google 搜索

在 NodeJS 中使用 post 时出现错误 500TypeError: 无法解构 'req.body' 的属性 'name',因为它未定义

在全局对象上声明的函数

mongoose 7.0.3 使用运算符 $and 严格搜索日期

kubernetes 上的 nextjs 无法启动

将环境变量从 GitHub 操作传递到 json

nvm / node / npm: node 12 的 npm 比 node 14 的更新?

tsc:当我上传 React+next js 和 node 项目时,在 heroku 找不到

如何使用 superagent/supertest 链接 http 调用?

如何undo撤消 Object.defineProperty 调用?

从 CoffeeScript 中的数组中删除一个值

nodejs:Ajax 与 Socket.IO,优缺点

Node.js 连接仅适用于本地主机

要求('babel/register')不起作用

响应分块时获取整个响应正文?

AWS Lambda 函数写入 S3

Mongoose - 验证邮箱语法