Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 918
Carol M Avatar asked Mar 05 '23 14:03

Carol M


1 Answers

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;
  // ...
}
like image 121
hdorgeval Avatar answered Apr 06 '23 13:04

hdorgeval