TestCafe beforeEach hook - how to execute a function and declare a variable
Asked Answered
V

1

5

I am using TestCafe and looking for a solution to do two things in a beforeEach hook: 1. execute a function (login before each test) 2. create unique test data

I am able to achieve both separately, but not both in the same hook:

This works to log in a user:

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

And this works to create new test data for each test case:

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

But I have not found a solution to achieving both in a single hook. And, I understand from the documentation that using two beforeEach hooks will result in the first being overwritten.

My current implementation is to execute the login in the beforeEach hook and creating test data in each test case, which is more verbose than I'd like, e.g., each test case contains

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

Advice would be greatly appreciated!

Vitiated answered 1/2, 2019 at 15:0 Comment(0)
L
8

One solution is to use the Test Context to prepare any kind of data context before each test execution

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;
  // ...
}
Leash answered 1/2, 2019 at 16:49 Comment(1)
Thank you for the advice! Since my goal was to not declare test data variables in each test case, I implemented the test context solution in my beforeEach hook as t.ctx.lastName = faker.name.lastName() and am calling it in each test case ast.ctx.lastName. Works exactly as I'd hoped.Vitiated

© 2022 - 2024 — McMap. All rights reserved.