Search code examples
playwright

Call a rest webservice inside Playwright test script


I'm starting to learn typescript and Playwright, and I need to make a GET call inside a Playwright test.

This call is for creating a session and will return a json with a SESSION_ID that I'll include later in the URL.

Thanks, Jose.

I've tried by adding jquery dependences: npm i --save-dev @types/jquery, but running this code:

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
  var settings = {
    "url": "http://xxxxxx.yyyyyy.com:8080/ords/hero_ords/heroapps/v1/mysession",
    "method": "GET",
    "timeout": 0,
  };

  $.ajax(settings).done(function (response) {
    console.log(response);
  });
});

I get this error: ReferenceError: $ is not defined

Thanks, Jose.


Solution

  • $.ajax is a jQuery call. JavaScript and TypeScript have the Fetch API that does the same thing without requiring extra libraries and works with `await:

    var response=await fetch(url);
    var data=await response.json();
    

    Running on Node

    Node.js versions before 18 didn't support the Fetch API. Trying to use it results in ReferenceError: fetch is not defined. The solution, described in this SO question is to either use a newer Node version or install the node-fetch package with:

    npm install node-fetch
    

    The best option is to use Node 18. By now, Node 18 is the only version in active support. It's an LTS version supported until 2025. Node 17 is already out of support and the previous LTS version, 16, is in Security support which expires in September 2023