skip to Main Content

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


  1. Chosen as BEST ANSWER

    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

    const { test, expect} = require('@playwright/test');
    
    const randomFigures = Math.random().toString();
    const randomAssetNumber = 'Asset' + randomFigures.substr(0, 8).toString()
    
    exports.expect = expect
    
    exports.test = test.extend({
        postTruck: async ({request}, use) => {
            const apiResponse = request.post('https://myFullUrl.com/api/Truck', {
                headers: {'Authorization': 'ApiKey my-api-key'},
                data: {
                    "ClientId": 1234,
                    "AssetNumber": randomAssetNumber
                },
            })
            await use(request) // thank you for this - was having problems figuring out where this needed to be
        },
    
    });
    

    and the test.spec.js calling that fixture in beforeEach hook which now passes:

    const { test, expect } = require('../custom-commands/customFixtures');
    
    test.beforeEach(async ({ postTruck }) => {
        const response = postTruck;  // <-- using the fixture value
        //expect(response.status()).toBe(200); 
        //gets Request context disposed so commented out & will research fixing that piece.
    });
    
    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("https://playwright.dev");
        await expect(page).toHaveURL(/playwright/);
    });
    

    this ChecklyHQ video was helpful also. https://www.youtube.com/watch?v=2O7dyz6XO2s


  2. 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.

    import { test as base, expect } from "@playwright/test";
    
    const randomFigures = Math.random().toString();
    const randomAssetNumber = "Asset" + randomFigures.substr(0, 8).toString();
    
    const test = base.extend({
      postTruck: async ({ request }, use) => {
        const apiResponse = await request.get("https://swapi.dev/api/planets/1/", );
        await use(apiResponse); // <--- pass the response to the test
      },
    });
    
    test.beforeEach(async ({ request, postTruck }) => {
      const response = postTruck;  // <-- using the fixture value
      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("https://playwright.dev");
      await expect(page).toHaveURL(/playwright/);
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search