Search code examples
javascripte2e-testingplaywright

File upload whit playwright change name on file (setInputFiles)


I'm moving e2e tests from cypress to playwright but have a problem. In cypress you can rename the file on upload but I can not find that you can do this with playwright. Dose anyone know it this is possible?

The system I am testing needs to have unique files so I need to rename the file to upload it.

Playwright:

await page.locator('input[type=file]').setInputFiles('../image.png');

Cypress:

cy.fixture('../image.png', { encoding: null }).as('testImage');
cy.get('input[type=file]').selectFile(
 {
    contents: '@testImage',
    fileName: mediaFileName,
    lastModified: Date.now(),
  },
  { force: true },
);

Solution

  • You can do this also in playwright. setInputFiles https://playwright.dev/docs/api/class-locator#locator-set-input-files supports object with name/type/buffer.

    Here is an example how to do it.

    test('should do upload file with different name.', async ({page}, testInfo) => {
        await page.goto('https://tmpfiles.org/');
    
        const fileBuffer = fs.readFileSync('dummy.test.txt')
        const uploadInput = page.locator('input[name=\'file\']');
        const newFileName= '1234abc.txt'
        await uploadInput.setInputFiles({buffer: fileBuffer, name: newFileName, mimeType: 'text/plain'});
    
        const uploadBtn = page.locator('input[name=\'upload\']')
        await uploadBtn.click();
    });
    

    The property name that you provide will be used for file upload.