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!
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;
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With