【问题标题】:TestCafe beforeEach hook - how to execute a function and declare a variableTestCafe beforeEach 钩子 - 如何执行函数并声明变量
【发布时间】:2019-02-01 15:00:31
【问题描述】:

我正在使用 TestCafe 并寻找在 beforeEach 钩子中做两件事的解决方案: 1.执行一个函数(每次测试前登录) 2.创建独特的测试数据

我可以分别实现,但不能在同一个钩子中实现:

这适用于登录用户:

fixture('My Component')
  .beforeEach(login(user, password)
)

这可以为每个测试用例创建新的测试数据:

fixture(`My Component`)
  .beforeEach(async t => {
    randomLastName = faker.name.lastName();
})

但我还没有找到在一个钩子中实现这两者的解决方案。而且,我从文档中了解到,使用两个 beforeEach 挂钩将导致第一个被覆盖。

我目前的实现是在 beforeEach 钩子中执行登录并在每个测试用例中创建测试数据,这比我想要的更详细,例如,每个测试用例包含

test('My Test', async (t) => {
  let randomLastName = faker.name.lastName();
  // ...
}

建议将不胜感激!

【问题讨论】:

    标签: javascript testing automated-tests e2e-testing testcafe


    【解决方案1】:

    一种解决方案是在每次测试执行之前使用Test Context 准备任何类型的数据上下文

    fixture('My Component')
      .beforeEach(async (t) => {
        // login method
       login(user, password);
       // inject test data in the test context
       t.ctx.inputData = {
          randomLastName: faker.name.lastName()
       };
    });
    
    test('My Test', async (t) => {
      // read test data from test context
      const inputData = t.ctx.inputData;
      const randomLastName = inputData.randomLastName;
      // ...
    }
    

    【讨论】:

    • 感谢您的建议!由于我的目标是不在每个测试用例中声明测试数据变量,因此我在 beforeEach 挂钩中将测试上下文解决方案实现为t.ctx.lastName = faker.name.lastName(),并在每个测试用例中将其调用为t.ctx.lastName。正如我所希望的那样工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多