Search code examples
typescriptplaywright

POM for API calls in Playwright


I would like to transfer the following code from example.test.ts file to commonOperations.ts file

test('Test name', async ({ request }) => {
  let response = await request.put(`${process.env.BASE_URL}/import`, { headers: { authorization: `Bearer ${token}` }, data: JSON.parse(quizSamples.getQuizData(2, 2, 100, 200)) });
  expect(response.status()).toBe(200);
});

In commonOperations.ts file a have a class with newly created method importQuizBE:

export class CommonOperations {
    readonly page: Page;
    constructor(page: Page) {
        this.page = page;
    }

    async importQuizBE(request: any, token: any, quizData: any, expectedStatus: number) {
        let response = await request.put(`${process.env.BASE_URL}/import`, { headers: { authorization: `Bearer ${token}` }, data: JSON.parse(quizData) });
        expect(response.status()).toBe(expectedStatus);
    }
}

Then I update the example.test.ts file:

test('Test name', async ({ request }) => {
  const comOperations = new commonOperations.CommonOperations(page);
  let response = comOperations.importQuizBE(request, token, quizSamples.getQuizData(2, 2, 100, 200), 200)
});

However, I am getting an error: Request context disposed.. Maybe somebody knows how to properly transfer API calls so I can reduce repetitive code and used it multiple times? Thank you!


Solution

  • I suppose you should add 'await' for 'importQuizBE' method's usage:

    test('Test name', async ({ request }) => {
      const comOperations = new commonOperations.CommonOperations(page);
      let response = await comOperations.importQuizBE(request, token, quizSamples.getQuizData(2, 2, 100, 200), 200);
    });