首页 > 解决方案 > 如何在 Cypress 中实现可重用的 `describe()` 或 `it()`

问题描述

我目前编写了一组规范来测试用户访问矩阵(具有不同创建/编辑/查看功能的不同用户类型)。

目前是这样实现的

describe('Test Description', function() {
  before(function() {
    // before test implementation
  });
  beforeEach(function() {
    // beforeEach test implementation
  });
  describe('A', function() {
    it(`should display Hello`, function() {
      // test implementation
    });
  });
  describe('B', function() {
    it(`should display Hello`, function() {
      // test implementation
    });
  });
  describe('C', function() {
    it(`should display Hello`, function() {
      // test implementation
    });
  });
});

我正在尝试“分组”

it(`should display Hello`, function() {
  // test implementation
});

这里是可重用的describe()it()当前/不同的规范文件,而不是到处都有相同的代码,因为我只是在每个规范文件中记录不同类型的用户,这些规范通常具有相同的describe()it()块。

我试过了

describe('Test Description', function() {
  before(function() {
    // before test implementation
  });
  beforeEach(function() {
    // beforeEach test implementation
  });
  describe('A', function() {
    itDisplayHello();
  });
  describe('B', function() {
    itDisplayHello();
  });
  describe('C', function() {
    itDisplayHello();
  });
});

const itDisplayHello = () => {
  it(`should display Hello`, function() {
      // test implementation
  });
};

我在运行时遇到了这个错误

The following error originated from your test code, not from Cypress.

  > Cannot access 'itDisplayHello' before initialization

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.

任何有提示或建议的人都会在这里不胜感激,谢谢!

标签: javascriptautomationautomated-testscypress

解决方案


这不是太难。也许从箭头函数更改为普通函数,因为 Javascript 会“提升”那些(就好像你把它放在规范的顶部一样)

参考吊装

function itDisplayHello() {
  it(`should display Hello`, function() {
      // test implementation
  });
}

或者将箭头版本放在规范的顶部。


推荐阅读