Matheus Bernardi
Matheus Bernardi

Reputation: 151

Testing API requests on localhost

I'm using Mocha and Chai to develop testing scripts for my API in Node.js. I have an endpoint called /measurements. This endpoint should return statusCode 200.

Here's how I trying to reach my goal:

var request = require("request");
var chai = require("chai");
var expect = chai.expect;


// Criamos nosso primeiro caso de teste e fornecemos uma descricao utilizando describe
describe("Teste monitora-sec", function () {

    it("Deve receber as medições", function (done) {
        request.get('localhost:3000/measurements')
            .expect(200)
            .end(function (err, res) {
                expect(res.body).to.have.lengthOf(506);
                done(err);
            });
    });
});

When I run mocha on gitbash, I get this error:

Teste monitora-sec
    1) Deve receber as medições


0 passing (34ms)
1 failing

1) Teste monitora-sec
    Deve receber as medições:
    Error: Invalid protocol: localhost:
    at Request.init (node_modules\request\request.js:458:31)
    at new Request (node_modules\request\request.js:127:8)
    at request (node_modules\request\index.js:53:10)
    at Function.get (node_modules\request\index.js:61:12)
    at Context.<anonymous> (test\measurement.spec.js:11:17)

What am I doing wrong?

[EDIT]

SOLUTION

Change the code a little bit:

var request = require("request");
var chai = require("chai");
var expect = chai.expect;
var urlBase = "http://localhost:3000";

describe("Teste monitora-sec", function () {

    it("Deve receber as medições", function (done) {
        request.get(
            {
                url: urlBase + "/measurementsLast"
            },
            function (error, response, body) {

                // precisamos converter o retorno para um objeto json
                var _body = {};
                try {
                    _body = JSON.parse(body);
                }
                catch (e) {
                    _body = {};
                }

                expect(response.statusCode).to.equal(200);

                done(); // avisamos o test runner que acabamos a validacao e ja pode proseeguir
            }
        );
    });
});

One of the problems was that I wrote just localhost:3000. Should be http://localhost:3000

Upvotes: 1

Views: 20628

Answers (1)

James Gould
James Gould

Reputation: 4702

The issue is that localhost:3000 isn't a valid address.

Change it to be http://localhost:3000 and the request will be fine.

Upvotes: 3

Related Questions