When attempting to run a Typescript Playwright test in Visual Studio Code's debug mode, it inexplicably fails to execute

I am fairly new to TypeScript and Playwright, but I have experience in coding. I believe I have a good understanding of what I am trying to achieve, but I am encountering a problem that I can't seem to figure out. I'm hoping someone can help me.

My project involves multiple TypeScript files where one file contains individual API calls and the other file orchestrates these calls in a specific order. This separation helps me focus on setting up the test cases before executing them, making my tests more concise and organized.

The issue arises when I try to call the orchestrated API calls from the second file. While the individual calls work fine when called directly from the test, they fail when encapsulated in a method within another file. Debugging this issue has proven challenging as the execution abruptly fails back to the test level without clear error messages.

The individual API call .ts file structure is as follows: -

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

module.exports = {
    authorisation: async function ( request: any ){
        dotenv.config();
        
        const response = await request.post(`myURL`, {
                    
            data: {     
                stuffs
            }
            });
    
        const token = JSON.parse(await response.text());
        return token.access_token;
    }
}

Calling this from a test like below works fine:

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

const API_Calls = require("./common/API_Calls");

test('Do the thing', async ({ page, request }) => {    
  var authtoken = await API_Calls.authorisation(request);
  ...execute the rest of the test logic...
});

However, when attempting to consolidate all calls into a "collection" .ts file, the failure occurs at the specified point:

import {expect, request} from '@playwright/test';
const API_Calls = require("./API_Calls");

module.exports = {

    doAllTheThingsForMe: async function (ADetailsJson: string, BDetailsJson: string, request: any){

        const authtoken = await API_Calls.authorisation(request); <--this is where it dies
        ...continue with the remaining actions...
}

And running this setup through a test results in the following error message:

 1) My Testies API.spec.ts:49:5 › Do that long test
 ─────────────────────────────

    TypeError: finalResponse.status is not a function

      50 |   var finalResponse = Group_API_Calls._doAllTheThingsForMe("AString","BString");
      51 |
    > 52 |   const responseCode = finalResponse.status();
         |                                      ^
      53 |
      54 | });
      55 |

If I manually include all individual calls in each test, it works fine, but that's not an efficient approach for repetitive testing scenarios. Any suggestions or insights would be greatly appreciated!

Answer №1

The main issue lies in the fact that you are not using the await keyword with the call to

var finalResponse = Group_API_Calls.doAllTheThingsForMe("AString","BString");
.

Because doAllTheThingsForMe is an asynchronous function, it will return a promise. To access the actual value it returns, you must first use the await keyword.

Therefore,

var finalResponse = await Group_API_Calls.doAllTheThingsForMe("AString","BString");`

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve all articles from a user using the TypeORM - findAll function

Is there a way to retrieve all articles of a specific user using the TypeORM package? In Sequelize, I have the following function: async findAllByUser(userUuid: string, findOptions: object): Promise<Article[]> { return await Article.findAll< ...

Seamlessly incorporating Storybook with Tailwind CSS, Create Next App, and TypeScript

*This is a new question regarding my struggles with integrating Storybook and Tailwind CSS. Despite following the recommended steps, I am unable to make Tailwind work within Storybook. Here's what I've done: I started a TypeScript project from s ...

Issue with React Context: The type 'Dispatch<SetStateAction<GiftsType>>' cannot be assigned to type '(arr1: string[], arr2: string[]) => void'

I'm currently working on a project in React+TS where I need to create a context that takes two string arrays and updates an object's state with these arrays. I keep encountering a title typo error in the setChoices function inside the return stat ...

Encountering an issue while trying to load a file from an API due to difficulties in parsing it to

When trying to load an xlsx file from an API, I encountered an error because Angular automatically tries to parse the body as JSON. To resolve this issue, I found that specifying the response type directly in the request works: this.http.get(this.url + " ...

Incorporating quotes into a unified npm script

I'm trying to merge two npm scripts into one, but the result is incorrect and causes issues with passing flags. I can't use the dotenv package, and using ampersands isn't solving the problem. Here's what I have in my package.json file ...

Updating data in Angular reactive forms using asynchronous dropdowns

I am currently developing an Angular application and have encountered an issue that I am unable to resolve by solely reading the documentation. One of the components in my application is responsible for displaying a form: https://i.stack.imgur.com/p5KEU. ...

What is the best way to retrieve a specific field from the observable data stream?

When working with observables, I often find myself using them like this: ... const id = 1337; this.service.getThing(id).subscribe( suc => doSomething(suc.name), err = doSomethingElse() ); Lately, I've been utilizing the async pipe more freque ...

How can I upload multiple images in one request using Typescript?

HTML: <div> <input type ="file" (change)="selectFiles($event)" multiple="multiple" /> </div> Function to handle the change event selectFiles(event) { const reader = new FileReader(); if (event.target.files & ...

Resolving a persistent AngularJS 1 constant problem with Typescript

I'm currently developing an application using TypeScript and AngularJS 1, and I've encountered a problem while trying to create a constant and passing it to another class. The constant in question is as follows: module app{ export class A ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

Show a nested JSON object when the specific key is not recognized

I received the following data from my API: { "id": 82, "shortname": "testing2", "fullname": "test2", "address": "addrtest2", "telephone" ...

You have encountered an issue with the runtime-only build of Vue, which does not include the template compiler

Lately, I have been utilizing Vue in a project and encountered an issue where upon compiling, my browser page displays as white with an error message stating "You are using the runtime-only build of Vue where the template compiler is not available. Either ...

The module '@/assets/icons/pay/pay-success.png' cannot be located, along with its corresponding type declarations.ts

Recently, I encountered an issue while trying to import a png image in my Typescript code. Here is the snippet of code that caused the error: import paySuccessIcon from "@/assets/icons/pay/pay-success.png"; When I tried to import the image, Visual Studio ...

tips on how to export an object with a specified data type

I need to restrict the type of exported function for my module type Request = ItemGetRequest | ItemUpdateRequest<Property> type Response = Property | ItemUpdateResponse<Property> type Handlers = {[key: string]: Handler<Request, Response> ...

The absence of typings.json in Typescript is creating an issue

As of now, I am encountering the following error during compilation: typings.json is missing In my existing packages.json, I have included the following dependency: "devDependencies": { "typescript": "^2.6.1", ... } Do you have any suggestion ...

The issue with angular JavaScript in the child component is causing the left side navigation dropdown to malfunction

I'm currently facing an issue with the left side navigation in my home component. The dropdown functionality is not working within one of the routing modules (admin-routing.module.ts). Interestingly, the navigation works perfectly fine in app-routing. ...

Accessing the state from a child functional component and then adding it to an array of objects in the parent component

I'm facing a challenge with a parent component that needs to manage the data of its child components stored in an array of objects. My goal is to add new child components and maintain their information within the parent's state as an array of obj ...

What is the method in AngularJS2 for using TypeScript to inject dependencies into components?

I have been encountering different methods of injecting dependencies into my component and not all of them seem to be working for me. I am curious about the advantages and disadvantages, what the recommended best practices are, and why some methods are not ...

Creating TypeScript domain objects from JSON data received from a server within an Angular app

I am facing a common challenge in Angular / Typescript / JavaScript. I have created a simple class with fields and methods: class Rectangle { width: number; height: number; area(): number { return this.width * this.height; } } Next, I have a ...

Typescript is throwing an error when trying to use MUI-base componentType props within a custom component that is nested within another component

I need help customizing the InputUnstyled component from MUI-base. Everything works fine during runtime, but I am encountering a Typescript error when trying to access the maxLength attribute within componentProps for my custom input created with InputUnst ...