What is the best way to upload a file using a relative path in Playwright with TypeScript?

Trying to figure out how to upload a file in a TypeScript test using Playwright.

  const fileWithPath = './abc.jpg';
  const [fileChooser] = await Promise.all([
    page.waitForEvent('filechooser'),
    page.getByRole('button', { name: 'Add a Photo' }).click(),
  ]);
  await fileChooser.setFiles([fileWithPath]);

Encountering an error when attempting this:

Error: ENOENT: no such file or directory, stat './abc.jpg'

If I switch the file path to an absolute one, it works:

const fileWithPath = '/Users/private/d/ionic/tests/playwright/optional/abc.jpg';

However, as I develop on macOS but run tests on linux, I would prefer to have the image file (abc.jpg) stored in the same folder as the test and use a relative path that works across operating systems. Any suggestions on how to achieve this?

Answer №1

With a helpful tip from @jonrsharpe and guidance from the file-chooser documentation, I devised this effective solution:

  import * as path from 'path';

  const fileWithPath = path.join(__dirname, 'abc.jpg');
  const [fileChooser] = await Promise.all([
    page.waitForEvent('filechooser'),
    page.getByRole('button', { name: 'Add a Photo' }).click(),
  ]);
  await fileChooser.setFiles([fileWithPath]);

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

Having trouble decoding a cookie received from a React.js front-end on an Express server

When using React js for my front end, I decided to set a cookie using the react-cookie package. After confirming that the request cookie is successfully being set, I moved on to configure the Express server with the cookie parser middleware. app.use(cookie ...

Can a standard tuple be matched with its corresponding key?

This code snippet showcases a function that can recognize that the key "banana" cannot have the value "red": type Fruits = { banana: 'yellow' | 'green' strawberry: 'red' } const fruit = <K extends keyof Fruits>(modu ...

How to access the result without using subscribe in Angular?

I am facing unexpected behavior with a method in my component: private fetchExternalStyleSheet(outerHTML: string): string[] { let externalStyleSheetText: string; let match: RegExpExecArray; const matchedHrefs = []; while (match = this.hrefReg.exe ...

Error: The function type 'Dispatch<SetStateAction<string>>' cannot be assigned to the type '(value: OptionValue) => void'

I recently dove into the world of integrating Typescript generics with React after reading this insightful article. I followed the code provided in the article, but encountered the following error: Type 'Dispatch<SetStateAction<string>>&ap ...

The React DOM isn't updating even after the array property state has changed

This particular issue may be a common one for most, but I have exhausted all my options and that's why I am seeking help here. Within my React application, I have a functional component named App. The App component begins as follows: function App() ...

Distinguishing variations within subcategories that stem from a common origin

In my code example, I have two interfaces that both extend a common base interface. The "String" function takes an argument of type "StringAsset". My expectation was that if I were to call the "String" function and pass it a value of "NumberAsset", TypeScr ...

Adding Profile Photos to Authenticated User Accounts in Firebase / Ionic: A Step-By-Step Guide

I have thoroughly gone through the Firebase Docs on "Managing Users" for web along with watching their instructional video on YouTube. Despite following the code they provide, I am encountering an error message that states: "Property 'afAuth' do ...

Determine the generic types of callback in TypeScript based on the argument provided

There are numerous Stack Overflow questions that share a similar title, but it seems none of them address this particular inquiry. I'm in the process of developing a wrapper for an express RequestHandler that can catch errors in asynchronous handlers ...

Create categories for static array to enable automatic suggestions

I have a JavaScript library that needs to export various constants for users who are working with vscode or TypeScript. The goal is to enable auto-complete functionality for specific constant options. So far, I've attempted to export a Constant in th ...

Dragging and dropping elements onto the screen is causing them to overlap when trying

I am having trouble merging the drag and drop functionality from Angular Material with resizing in a table. Currently, both features are conflicting and overlapping each other. What I am hoping for is to automatically cancel resizing once drag and drop s ...

Writing Data to Google Cloud Firestore Map using NextJS and Typescript with nested objects

I could use some assistance. I'm developing an application using NextJS (React), TypeScript, and Google Cloud Firestore. Everything seems to be working fine so far. However, I'm facing an issue with storing the address and phone number in a neste ...

The concept of callback function overloading using generic types in TypeScript

Is there a way to define a callback type in TypeScript that can accept a variable number of generic type arguments while keeping the number of arguments fixed? For instance: export interface CustomFn { <T1>(value1: T1): boolean <T1,T2>(va ...

unable to assign an array to a different array in typescript

I'm facing an issue with assigning values to the private kitems array in my class. Despite defining it as kitems:any[], when I try to assign a value using this.kitems = items; and then log this.kitems, it shows up as an empty array. createprofile() { ...

Creating generic output types in TypeScript based on the input types

In my React-Native project, I'm focusing on implementing autocomplete and type validation. One of the challenges I'm facing is configuring the types for the stylesheet library I am using. A customized stylesheet is structured like this: const s ...

What could be the reason behind the error related to react-router-dom?

index.tsx import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement ); root.render( <React.S ...

React: Function is missing a return type declaration. eslint plugin @typescript-eslint urges for explicit function return types

I'm just starting out with Typescript in React. I've created a simple functional component, but eslint is giving me an error saying that the return type for the functional component itself is missing. Can anyone help me figure out what I'm d ...

developed a website utilizing ASP MVC in combination with Angular 2 framework

When it comes to developing the front end, I prefer using Angular 2. For the back end, I stick with Asp MVC (not ASP CORE)... In a typical Asp MVC application, these are the steps usually taken to publish the app: Begin by right-clicking on the project ...

Issue occurred while trying to set the value from an API call response in the componentDidMount lifecycle method

There is a boolean variable disableButton: boolean; that needs to be set based on the response received from this API call: async getDocStatus(policy: string): Promise<boolean> { return await ApiService.getData(this.apiUrl + policy + this.myEndpo ...

Exploring Angular 4's capability: Incorporating data from Http Post Response into a .js file or highchart

I'm a beginner with Angular 4. I'm trying to create a dashboard that pulls data from an Http Post Response and I want to use this data to create a Chart (Highchart). I have successfully received the response in the console.log and formatted it i ...

What is the best way to define a precise return type for a JSX Element?

Is it possible to define a function that returns a Button element and what would the correct return type of the function be? For example: Ex: const clickMeButton = (): Button => { return ( <Button> Click Me </Button& ...