node.jstypescriptplaywrightplaywright-testplaywright-typescript

How to upload file to API test


I use playwright to write API integration tests. I need call an API that uploads the file.

In the project I have a static assets folder:

/static-assets
   - import.xlsx

How do I reference the file so that I can make the API call?

import { request } from '@playwright/test';
const context= request.newContext();
await context.fetch(url, {
  method: 'POST',
  data: ??
});

Solution

  • playwright allows to read from filesystem so you can use readFileSync from from 'fs';

    import { readFileSync } from 'fs';
    import { basename } from 'path';
    
    const filePath = 'static-assets/import.xlsx'; //either full path or relative to project dir
    const fileName = basename(filePath);
    const file = new File([readFileSync(filePath)], fileName);
    
    //in my case I needed multipart form data
    const form = new FormData();
    form.append('SomeOtherField', 'BlaBla') ;
    form.append("File", file);
    
    context.fetch(url, {
      method: 'POST',
      multipart: form,
    });