Is it possible to link together supertest requests that are reliant on one another?

Currently, the output shows:

Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises
Warning: .end() was called twice. This is not supported in superagent
GET /api/things 200 3.009 ms - 2414
superagent: double callback bug
WARNING

The issue I'm facing is that I require the res object from the first .end() call to test the ETag functionality. However, it never reaches the second .end() and doesn't log anything on the console.

The .catch(done) inside is the one triggering.

it('should return things', done => {
  const promises = [];

  promises.push(Thing.create(testThing));
  promises.push(Thing.create(testThing));

  Promise.all(promises)
    .then(things => {
      request(app)
        .get('/api/things')
        .expect(200)
        .end((err, res) => {
          const etag = res.get('ETag')
          if (err)
            return done(err);
          request(app)
            .get('/api/things')
            .set('If-None-Match', etag)
            .expect(304)
            .end((err, res) => {
              console.log('are we able to make it back here?');
              expect(err).to.not.exist;
              expect(res.body.data).to.be.undefined;
              expect(res.get('ETag')).to.be.equal(etag);
              return done(err);
            })
        })
        .catch(done);
    })
    .catch(done);
});
});

If anyone has insights on why this behavior occurs and how to approach testing it, your suggestions are welcome.

Answer №1

Spent an entire hour on this task.

The official documentation provided is lacking:
https://www.npmjs.com/package/supertest

The following solution worked correctly:

let request = require("supertest");
var assert = require("assert");
// const chai = require("chai");                     // can use chai instead of assert

describe("Run tests", () => {
  request = request("http://localhost:3001");        // must be placed here

  it("get", async () => {

    request
      .get("/")
      .expect("Content-Type", /json/)
      .expect(200)
      .then((response) => {                          // should be then, not a callback
        assert(response.body.data !== undefined);
      })
      .catch((err) => {
        assert(err === undefined);
      });

  });

});

Answer №2

After some investigation, I discovered my mistake:

if (req.header('If-None-Match') === allThingsEtag) {
    // don't send allThings
    res.status(304);
}

The key was to actually set the body of the response for it to be returned, like this:

if (req.header('If-None-Match') === allThingsEtag) {
    // don't send allThings
    res.status(304);
    res.json();
}

This solution may be very specific to my situation, but if anyone else encounters this issue, they might find this helpful. Make sure to check your API code.

To address the problem of calling .end() twice, I adjusted my tests to use .then().

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

Creating a critical section in a multi-instance Node.js application in a Kubernetes environment - a step-by-step guide

Recently, I encountered a situation where an interval is set up in Node.js to send periodic emails in a MEAN stack application running on multiple instances in a Kubernetes deployment. However, I noticed that the interval was triggered for all instances ...

Having trouble with React Testing Library throwing an error every time I try to use fireEvent on an input text?

When attempting to utilize the "fireEvent" method from React Testing Library, I encountered an error as shown below: MainSection.test.js: test('Verifying SearchBar functionality', async () => { render(<SearchBar />); const text ...

Aligning node.js requests with corresponding responses

As a beginner in Web programming, I have a question regarding how request/response pairs are matched up for asynchronous requests. For instance, if I have an asynchronous jQuery request calling a server using node.js, both of which are asynchronous, how ...

npm modules encountering corrupted package.json files

I'm facing an issue where my modules' package.json files are getting corrupted with random garbage characters like "♥?????PB?8?N???↨☻??lp`↨T▼?◄♂?U". This corruption seems to happen spontaneously without any obvious triggers. Initial ...

The current version of npm for @angular 2 has not been released yet

Looking to transition from Angular 2 Beta 15 to Angular 2 RC1. Currently utilizing Visual Studio 2015. Within my npm package.json in Visual Studio, I've inputted: "dependencies": { "@angular/core": "Unavailable", } However, it displays as unav ...

The information seems to not be getting transferred to the req.body variables from the HTML form

Within my server-side settings using knex and express, I have defined the following function: // POST: Create new users app.post('/add-user', (req, res) => { const {firstName, lastName, emailAdd, gender, dob, password} = req.body; cons ...

order documents in a subdocument by date with mongoose and node.js

Having difficulty sorting posts by the date of updated_at instead of creation? The code snippet provided currently displays posts in order of creation, but you need them to be sorted by the updated date. See the schema and route code below for reference: ...

Updating the color scheme of the selected nav-item and showcasing the corresponding page in relation to the navbar selection

I have been trying various methods, but I am unable to change the background color of an active navigation item and also display the corresponding page. Important: The jQuery code below successfully changes the background color of the navbar list item. Ho ...

Encountered an npm compilation error - Unable to locate module: bootstrap-theme.css

I recently updated all the dependencies in my JavaScript program without making any changes to my components or index.js file. However, when I run npm run build I encounter an error with index.js related to bootstrap-theme.css: Failed to compile. Modul ...

Session management functions properly in Postman, however, encountering issues when attempting to use it on a web

Working on a NodeJS project using express-session to handle sessions. When sending a post request to http://localhost:5500/login, a session is created with an additional property userid. Upon making a get request to http://localhost:5500/ using Postman, th ...

Strategies for managing multiple request keys that share the same value

In the process of this project, I am creating models and passing values from a POST request's body. My main objective is to properly define these models. Here is a JSON sample that I intend to post to MongoDB: { "signageId": "5cd857c4965f863b7c8 ...

AJV is failing to validate my body using the function generated by the compile method

Currently, in my API development process with express, I have implemented AJV as a middleware to validate the incoming body data. The version of AJV being used is 6.12.6 Below is the JSON schema named body-foobar.json: { "type": "object& ...

Guidelines for managing UnprocessedItems with the AWS JavaScript SDK for dynamoDB

Currently, I'm facing an issue while attempting to utilize an AWS Lambda function for handling events from SendGrid. The event is expected to be in the form of an array containing a variable number of JSON objects, each representing a specific event. ...

What could be causing this async function in NodeJS to not catch the error?

I am puzzled by the behavior of the catch block in the upload function failing to capture the exception thrown after the request(...) line within the createReleaseVersion function. The nodejs script crashes and the exception goes unhandled, with only the e ...

What is the best way to determine the NODE_ENV in which the Express app is currently operating?

Is there a way to retrieve the current value of NODE_ENV (whether it is development or production) within an Express codebase without using app.configure('production' function(){})? ...

Encountering an external babel register error when trying to initiate npm start

I initiated my angular Application using npm start with gulp and babel enabled. However, upon starting, the browser continuously loads and displays an error message stating "requiring external babel register". Below are the logs from the terminal: [19:52 ...

Installing npm packages on Kudu doesn't seem to have any effect

Earlier today, I executed npm install and the node_modules directory was created with all the necessary files. However, a few hours later, when I ran the same command with the same package.json file, there were no errors, but the node_modules directory wa ...

Encountering issues while trying to update npm in a Angular 6 project

Attempting to upgrade npm from version 6.1.0 to 6.4.0 using the command line interface: npm install -g npm Unfortunately, encountered an error during the update process. npm ERR! path /usr/local/lib/node_modules/npm/node_modules/ansi-regex npm ERR! co ...

Retrieve an object using a variable

Essentially, my question is how to extract a value from a variable and input it into a sequence. Being Dutch, I struggle to articulate this query correctly. var channelname = msg.channel.name; "description": `${config.ticketlist.channelname.ticketmessage} ...

Determining whether a path is absolute or relative: A step-by-step guide

Is there a universal function in node.js that can determine if a given path is absolute or relative? Unlike Windows, which starts with 'C:' or '\', UNIX paths begin with '/'. ...