Struggling with capturing HTTP requests for testing file downloads

I am attempting to recreate the functionality found at:

The page I am working on has a target="_blank" attribute, is it possible to remove this attribute?

This currently causes the test to fail.

The purpose of the code example provided is not entirely clear. Must the URL be that of the page containing the download link?

import { ClientFunction, t, Selector, RequestLogger } from 'testcafe'
import * as fs from 'fs';
import * as path from 'path';
...
const forInvoice = new ForInvoice()
const client = 'STRV s.r.o.'

const url = urlFor('?/timers/unbilledOverview')
const logger = RequestLogger({ url, method: 'post' }, {
logResponseHeaders: true,
logResponseBody:    true
});

fixture.only `For Invoicing`
   .requestHooks(logger);

test('Verify download of .xls and .pdf', async t => {
    await t.useRole(ADMIN_INVOICE)
    await forInvoice.navigateToForInvoicing()
    await forInvoice.filterClient(client)
    await t
        .click(Selector('a').filter('.sc-mini-icon-file.excel-file'))
        .expect(logger.contains(r => r.response.statusCode === 200)).ok();

    const filePath = path.join(__dirname, 'STRV-s-r-o-Attachment');

    console.log(filePath);
    console.log(logger.requests[0].response.headers);

    fs.writeFileSync(filePath, logger.requests[0].response.body);

})

Answer №1

It has come to my attention that in the given example, the start page for the fixture or test was not specified, which could potentially be causing the error.

The TestCafe example mentioned entails the following steps:

  1. Setting up a RequestLogger instance to monitor requests (headers and body) on the same page where the test commences.
  2. Clicking a button to trigger the file download process.
  3. Waiting for the server's success response.
  4. Saving the response body to a file.

The url parameter within the filter object corresponds to the destination page of the request (documentation), and does not necessarily have to match the URL of the tested page.

To manipulate an element on the page, you can utilize ClientFunction with the standard Web API. Here is some code to help you get started:

import { Selector, ClientFunction } from 'testcafe'

const link = Selector('a');

const removeTarget = ClientFunction(() => {
    link().removeAttribute('target');
}, { dependencies: { link } })

fixture`Fixture name`
    .page`https://your_page.com/`;

test('Remove target', async t => {
    await removeTarget();
});

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

Adjusting the array when items in the multi-select dropdown are changed (selected or unselected)

I am looking to create a multi-select dropdown in Angular where the selected values are displayed as chip tags. Users should be able to unselect a value by clicking on the 'X' sign next to the chip tag, removing it from the selection. <searcha ...

What happens when Angular elements don't have an injector?

Exploring Angular's custom elements while steering clear of dependency injection is my current experiment. const MyElementElement = createCustomElement(MyElementComponent, { injector }); customElements.define('my-element', MyElementElement) ...

What is preventing typescript from inferring these linked types automatically?

Consider the following code snippet: const foo = (flag: boolean) => { if (flag) { return { success: true, data: { name: "John", age: 40 } } } return { success: false, data: null } ...

Managing HTTP requests with errors within a forEach loop in Angular 9

I am currently coding a script that iterates through an array to make HTTP requests. Most of these requests are directed towards non-existent resources, but I do not have information on which ones specifically. Here is the code snippet I am using: ...

Error message: "An issue has been encountered within Angular 4 where it is

Thank you for any assistance, I realize this may be a beginner question... but I seem to be missing something and my TypeScript code is error-free. My goal is simple: I want to track which Main Menu Item is currently selected. To achieve this, I have bou ...

Tips on leveraging separate files for classes in TypeScript

I'm currently working on developing a TypeScript application where each class is saved in its own .ts file. I prefer to use VS Code for this project. So far, my compile task seems to be functioning correctly (transpiling .ts files into .js files). How ...

How can I integrate the "FETCH FIRST n ROWS ONLY" feature into my Kysely DB query builder?

For my projects that are based on TypeScript, Prisma is my go-to DB toolkit. However, I recently encountered a project where Kysely, a type-safe DB query builder, was being used. I'm currently trying to create a query with Kysely that can handle keys ...

Can someone explain why the Next 13 API route is showing up as empty?

I am currently working with Next 13 and I am attempting to create a simple API route. My goal is to have a: "hi" returned when I visit localhost:3000/api/auth. Despite not encountering a 404 error or any errors in the terminal or console, I can&a ...

Tips for accessing a variable from a Global service in Ionic

I am currently working on developing an app using Ionic but experiencing some difficulties. I encountered an issue while trying to access a variable from a global service when it is imported to another page. Here is an example of the Global service (backen ...

Unable to locate dropdown menu component using Java Selenium

Each time I attempt to locate the initial dropdown menu (the state/province one) on this site using the Selenium ChromeDriver, it consistently results in an element not found error. Various methods have been attempted, including explicit waits, locating t ...

Execute an Asynchronous Operation in NgRx After Triggering an Action

Please note that this is a question seeking clarification Instructions Needed I am currently working on dispatching an action to NgRx in order to add a task to a list of tasks. Additionally, I need to perform a put request to an API to save the changes ma ...

What might be the underlying reason for Chrome displaying a net::ERR_FAILED error when attempting to make a request from a Vue frontend to a C# API using Axios?

I have a C# Backend+API that I interact with from my Vue Application using axios to make requests. In the C# code, there is an endpoint that looks like this: // GET: api/Timezone public HttpResponseMessage GetTimezoneData() { ...

I am facing issues with testing a service in Angular that utilizes the HttpClient

Currently, I am working on an Angular 5 Project, but it's not a major project. However, I haven't been involved in the Angular2+ environment since early 2.1/2.2. My issue revolves around a Service that makes a call to a public API. Unfortunately ...

Interacting between components using Angular 2 services

I am attempting to implement bidirectional service communication using Angular. I have followed the instructions provided in the documentation here: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service interactio ...

Ways to dynamically change values within a single Angular component when making multiple selections using mat-select

Imagine you're developing a cutting-edge pizza ordering application complete with a MenuComponent that showcases all the delicious menu items offered by the restaurant. Each item is presented as a unique card displaying all the essential information. ...

Exploring Angular 4.3 Interceptors: A Practical Guide

I am currently working on a new app that needs authorization headers. Normally, I follow a similar approach to what is described in this article on scotch.io. However, I have recently learned that Angular 4 now fully supports HTTP Interceptors through the ...

Filtering JSON data in Ionic 4 based on multiple values

Recently, I've encountered an issue with filtering a local JSON file based on multiple criteria. Initially, I thought that combining conditions using '&&' would solve the problem. However, when the data is loaded into Ngx-Datatable, nothing ...

Angular2 RC definitions are not recognized by tsc

Currently, I am utilizing angular version 2.0.0-rc.1, however, I am encountering issues with the typescript compiler (Typescript version 1.8.10). Whenever I run tsc on my project, I am bombarded with numerous errors similar to this one: app/app.componen ...

Incorporating FormControl Validators within a Child Component in Angular

Having two Angular Components, one is called parent.ts and the other is named child.ts. Parent.ts contains a Form group, while child.ts passes the Form data via CVA to the parent. Now, I am looking to create a reusable child component that can generate c ...

Leveraging data analytics for iOS-Calabash automated testing through the utilization of XML, CSS, and global

Currently, I am implementing automated testing with calabash-ios. My goal is to execute cucumber once and have it run multiple times for different usernames across a variety of test scenarios. The approach I want to adopt involves the following steps: Gi ...