I am trying to implement a fixtures helper file in Playwright so that certain data setup commands used by many tests can be better maintained v having all of these in every test spec that needs to create the same data. The same api call is working when placed within a test; however, when using it within a beforeEach hook, the POST call is made & gets a 200, but the test gets a timeout running the beforeEach hook. The POST is taking < 1s & I’ve set a timeout to 60s. I think I am having issues with the return in my fixture file. Not finding a ton of guidance. Would anyone be able to help identify where I’ve gone astray? Thanks for any assistance.
my fixture file:
const base = require('@playwright/test');
const randomFigures = Math.random().toString();
const randomAssetNumber = 'Asset' + randomFigures.substr(0, 8).toString()
// Extend base test by providing "postTruck".
// This new "test" can be used in multiple test files, and each of them will get the fixtures.
exports.test = base.test.extend({
postTruck: async ({request}, use) => {
return await request.post('https://myFullUrl.com/api/Truck', {
headers: {'Authorization': 'ApiKey my-api-key'},
data: {
"ClientId": 1234,
"AssetNumber": randomAssetNumber
},
})
},
});
exports.expect = base.expect;
and then the test spec which uses above fixture:
const { test, expect } = require('../custom-commands/customFixtures');
test.beforeEach(async ({ request, postTruck }) => {
const response = await postTruck(request);
expect(response.status()).toBe(200);
});
test('basic test to see that beforeEach is used', async ({ page, baseURL }) => {
console.log('my test is being run after beforeEach hook')
await page.goto('/')
await expect(page).toHaveURL(baseURL + '/Login.aspx')
})
2
Answers
thanks to @candre for help getting that cleaned up. adding the current state of my working beforeEach hook using an api call in a separate file since I have not found that design to be well represented in my playwright doc/example searches. I do still have some further things to work out to best include response assertions in particular. (Scrubbing urls again since they don't seem relevant to the test structure issues that I was running into).
customFixtures.js file
and the test.spec.js calling that fixture in beforeEach hook which now passes:
this ChecklyHQ video was helpful also. https://www.youtube.com/watch?v=2O7dyz6XO2s
You are calling the fixture like a function, which it isn’t. You also forgot to use the fixture in the test, which caused the test to halt.