Search code examples
typescriptvuejs3playwrightwebapi

Playwright test to test file download on window.open(url)


My project has Vue3 as frontend , and we are writing test for the app using playwright. My components has a download icon which on click triggers a handler which in turn gets the presignedUrl from S3. This presignedUrl is passed to windows.open(s3_URL).

Handler code:

await axios(url, requestOptionsGet) // Gets the presigned URL
    .then(response => {
      // logic to check for 200 or 400 response.
    })
    .then(async response => {
      const service_response = response as SERVICE_RESPONSE;
      const s3DownloadUrl = service_response?.url;
      window.open(s3DownloadUrl);// THIS OPENS the FILE in new window and basically gets downloaded.
    })
    .catch(errorResponse => {
      //hanlde
    });

I wan to write playwright test for the same. Could someone please suggest way to tackle this


Solution

  • Was able to test download of file using side effects of window.open(). The below is framework code and not the exact code since I cant share that.

    But this would give anyone fair idea of how I solved it.

    test('should open a new window with the given URL', async ({ page }) => {
      const landingPage = new LandingPage(page);
    
      // Listen for the 'popup' event which is triggered by window.open
      let newPagePromise = page.waitForEvent('popup');
      await givenAllNetworkCallMocked();// mock necessary network calls.
    
      // Navigate to your test page
      await page.goto('/'); // 
    
      await landingPage.fileDownloadButton.click();
    
      // Wait for the new window to open and get the new page
      const newPage = await newPagePromise;
    
      // Verify the URL of the newly opened page
      await newPage.waitForLoadState('load');
      const newPageURL = newPage.url();
      expect(newPageURL).toBe('https://example.com');
    });
    

    Explanation:

    1. Get hold of page and initialize all the locator with it(done in Landing page).
    2. you do waitForEvent('popup') this will return new page popup as a promise.
    3. Mock all the network calls you have which are necessary to mock.
    4. Now you goto the main page and do click on download button.
    5. await on promise to resolve and then assert URL for the page.

    Thats it.