Search code examples
javascriptnode.jsexpresssuperagent

superagent doesn't return response


I am trying to send request with query string this way but nothing is logged in the console. I want to do something with the returned result but res and err are both nothing.

superagent
        .get('http://localhost:4000/v1/process/web')
        .query({user: 'nux'})
        .then(res => console.log(res.body))
        .catch(e => console.error(e));

this how router looks like

const router = express.Router();

router.get('/web', async (req, res) => {
    res.send(req.query);
});

What is wrong with these codes?


Solution

  • Here is a minimal working example:

    app.js:

    const express = require("express");
    const router = express.Router();
    const app = express();
    
    router.get("/web", (req, res) => {
      res.send(req.query);
    });
    
    app.use("/v1/process", router);
    
    module.exports = app;
    

    app.test.js:

    const app = require("./app");
    const superagent = require("superagent");
    const { expect } = require("chai");
    
    describe("57953567", () => {
      let server;
      const port = 4000;
      before((done) => {
        server = app.listen(port, () => {
          console.info(`HTTP server is listening on http://localhost:${server.address().port}`);
          done();
        });
      });
      after((done) => {
        server.close(done);
      });
      it("should pass", () => {
        return superagent
          .get("http://localhost:4000/v1/process/web")
          .query({ user: "nux" })
          .then((res) => {
            console.log(res.body);
            expect(res.body).to.be.eql({ user: "nux" });
            expect(res.status).to.be.equal(200);
          });
      });
    });
    

    Integration test result with 100% coverage:

     57953567
    HTTP server is listening on http://localhost:4000
    { user: 'nux' }
        ✓ should pass
    
    
      1 passing (39ms)
    
    -------------|----------|----------|----------|----------|-------------------|
    File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
    -------------|----------|----------|----------|----------|-------------------|
    All files    |      100 |      100 |      100 |      100 |                   |
     app.js      |      100 |      100 |      100 |      100 |                   |
     app.test.js |      100 |      100 |      100 |      100 |                   |
    -------------|----------|----------|----------|----------|-------------------|
    

    Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57953567