0

I am trying to automatize the tests for an API using Mocha + Chai.

Right now, I have this code:

it("Correct request", function(done) {
  chai.request(url)
    .get(endpoint)
    .set("Authorization", "bearer " + token)
    .end(function(err, res) {
      expect(res).to.have.status(200);

      userAttrs.forEach((attr) => {
        expect(res.body[attr]).to.not.be.undefined;
      })

      done();
  })
});

it("No authorization request", function(done) {
  chai.request(url)
    .get(endpoint)
    .end(function(err, res) {
      expect(res).to.have.status(401);
      expect(res).to.be.undefined;
      done();
  })
});

And in console I am getting these results:

c:\workspace\functional-tests>npm test

> @ test c:\workspace\functional-tests
> mocha --timeout 50000 ./test/app/users/data.js



  APP endpoints
    GET /users/data
      √ Correct request (427ms)
      1) No authorization request


  1 passing (1s)
  1 failing

  1) APP endpoints
       GET /users/data
         No authorization request:
     Uncaught ReferenceError: expected is not defined
      at c:\workspace\functional-tests\test\app\users\data.js:54:21
      at Test.Request.callback (node_modules\superagent\lib\node\index.js:716:12)
      at IncomingMessage.parser (node_modules\superagent\lib\node\index.js:916:18)
      at endReadableNT (_stream_readable.js:1064:12)
      at _combinedTickCallback (internal/process/next_tick.js:138:11)
      at process._tickCallback (internal/process/next_tick.js:180:9)



npm ERR! Test failed.  See above for more details.

My question is... How can format the exception? I tried using the function catch, but it makes both tests to pass (in console, it says 2 tests passing, but it prints an error).

I also tried

expect(res).to.throw(Error);

and

done(err);

I want it to display an error message with a test that I would define.

Thank you in advance!!!

ovejaexiste
  • 661
  • 1
  • 6
  • 15
  • @VicJordan I am not asking why thrown errors are not been catching in my code. I am just asking how I can handle the errors when they are not expected and not using catch as it makes to display a wrong result in console. Thanks for your time. – ovejaexiste Aug 03 '18 at 14:53
  • You're trying to call a function `expected` which doesn't exist. I think you need to change it to `expect(res).to.be.undefined;` – sbrass Aug 03 '18 at 15:06
  • @sbrass no, with that corrected still displays errors in console the same way. Thank you. – ovejaexiste Aug 03 '18 at 16:03
  • I want the way to display unhandle errors in a different way, with right data this code is working, it is just an example to make the situation I want to show to appear. – ovejaexiste Aug 03 '18 at 16:07
  • "with that corrected still displays errors in console the same way" - you mean, it shows `expect is not defined`? – ischenkodv Aug 03 '18 at 20:25
  • @ischenkodv no, I did not mean that. I just said that it was a mistake on my comment. – ovejaexiste Aug 09 '18 at 09:00

0 Answers0