Search code examples
javascripttypescriptplaywrightplaywright-typescript

Playwright API receiving undefined value typescript


I've just started on my Playwright/Typescript journey so I'm a complete beginner at this point. A lot of this will potentially be no-no's so happy for these to be pointed out.

Use case: I have a really long end to end process and instead of hardcoding a variable I'm using an API to try and retrieve a random identifier from our records. To make this future proof as sometimes the records are removed etc.

When running a test my variables are storing as undefined. When trying to run assertions, store them for use later or printing them to the console I am encountering errors or undefined is being printed.

For the below I was expecting a pass/fail whether the field had a value. This produced an error:

Error: expect(received).toBeTruthy() Received: undefined at tests\tests\API_tests.spec.ts:29:41

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

test('API testing with a GET', async ({ request}) => {

    function myoffset(n){
        return Math.floor(Math.random() * (n + 1))};

const paras = {numrows: 1, offset: myoffset(400), TypeValue: 'TYPE', Locality: 'Place1', Town: 'Town1', Status: 'STAT'};
const myURL = 'https://myapi/url';
const response = await request.get(myURL, {params: paras });
expect(response.status()).toBe(200);

const responseBody = await JSON.parse( await response.text());
console.log(responseBody);
expect(responseBody.myJSON.myFIELD).toBeTruthy();

If I remove the last line the API response prints and the test passes.

If I swap the last line for a (probably poor) attempt at storing the myFIELD value as a variable

const myVAR = responseBody.myJSON.myFIELD;
console.log(myVAR);

The initial response prints as expected but when I expect the value from myFIELD to be printed I'm getting undefined.

{
  myJSON: [
    {
      myFIELD: 'value I want',
      TypeValue: 'TYPE',
      Locality: 'Place1',
      Town: 'Town1',
      Status: 'STAT'
    }
  ]
}
**undefined**
  1 passed (9.7s)

I'd appreciate any help/suggestions. I understand if this doesn't make any sense though.

Thanks


Solution

  • From what I can see from your JSON structure you are trying to index the field which is actually in an object inside an array. So your expect statement should be:

    expect(responseBody.myJSON[0].myFIELD).toBeTruthy();
    

    Note that this assumes that your body will always be of length = 1, which might not be the case, you can apply your own criteria here.