简体   繁体   中英

How to expect http error and response using chai in nodejs

Hi I am writing a unit test case of my function. this function returns a json response in case request is successful else return an error.

describe("Operations", async () => {

    it("user info", async () => {
        let accessToken = 'dfsf;
        const result = await authConnectors.getUser(accessToken);


    });

});

How to assert http error and response using chai in nodejs ?

{ Error: Unauthorized
    at Request.callback (/vagrant/node_modules/superagent/lib/node/index.js:699:13)
    at IncomingMessage.parser (/vagrant/node_modules/superagent/lib/node/index.js:903:18)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  status: 401,
  response:
   Response {
     domain: null,
     _events: {},
     _eventsCount: 0,
     _maxListeners: undefined,
     res:
      IncomingMessage {
        _readableState: [Object],
        readable: false,
        domain: null,
        _events: [Object],
        _eventsCount: 4,
        _maxListeners: undefined,
        socket: [Object],
        connection: [Object],
        httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers: [Object],
        rawHeaders: [Object],
        trailers: {},
        rawTrailers: [],
        upgrade: false,
        url: '',
        method: null,
        statusCode: 401,
        statusMessage: 'Unauthorized',
        client: [Object],
        _consuming: true,
        _dumped: false,
        req: [Object],
        text: '',
        read: [Function] },
     request:
      Request {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined,
        _agent: false,
        _formData: null,
        method: 'GET',
        url: 'https://id-dev',
        _header: [Object],
        header: [Object],
        writable: true,
        _redirects: 0,
        _maxRedirects: 5,
        cookies: '',
        qs: {},
        _query: [],
        qsRaw: [],
        _redirectList: [],
        _streamRequest: false,
        req: [Object],
        protocol: 'https:',
        host: 'id-dh',
        _endCalled: true,
        _callback: [Function],
        res: [Object],
        response: [Circular],
        called: true },
     req:
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedHeader: {},
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Object],
        connection: [Object],
        _header: 'GET oqcnM_4xWNbmv-WaoJ63UOjcZSHW-KrULLRUFzXrQKS6iuPWp6poHLjop1WsRtw5Y-KQCTZVI783awnn3_utEw6yqD6qpHHZwhxiPeM8mFZgN_zH4xX0ChbQ3ayao9Ms6ZHQT0X00N467HPfq5hVAW4D3a-3DURwnUvvVTIsYTShhZAsag2P26WDbKapPdgfVpjQKV-4GP--cLWbAZpEWJT3yS31YiY-VEcdfjdDU\r\nAccept: application/json\r\nConnection: close\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/userinfo',
        _ended: true,
        parser: null,
        res: [Object] },
     text: '',
     body: {},
     files: undefined,
     buffered: true,
     headers:
      { 'content-length': '0',
        'strict-transport-security': 'max-age=31536000; includeSubDomains; preload',
        'x-xss-protection': '1; mode=block',
        'x-content-type-options': 'nosniff',
        'content-security-policy': 'default-src \'self\';script-src \'self\' https://track.abc.net;style-src \'self\' \'unsafe-inline\' https://track.abc.net;img-src \'self\' https://track.abc.net;frame-src \'self\' https://track.abc.net;object-src \'none\';',
        'www-authenticate': 'Bearer error="invalid_token"',
        date: 'Wed, 28 Mar 2018 11:57:56 GMT',
        connection: 'close' },
     header:
      { 'content-length': '0',
        'strict-transport-security': 'max-age=31536000; includeSubDomains; preload',
        'x-xss-protection': '1; mode=block',
        'x-content-type-options': 'nosniff',
        'content-security-policy': 'default-src \'self\';script-src \'self\' https://track.abc.net;style-src \'self\' \'unsafe-inline\' https://track.abc.net;img-src \'self\' https://track.abc.net;frame-src \'self\' https://track.abc.net;object-src \'none\'',
        'www-authenticate': 'Bearer error="invalid_token"',
        date: 'Wed, 28 Mar 2018 11:57:56 GMT',
        connection: 'close' },
     statusCode: 401,
     status: 401,
     statusType: 4,
     info: false,
     ok: false,
     redirect: false,
     clientError: true,
     serverError: false,
     error:
      { Error: cannot GET /sts/connect/userinfo (401)
          at Response.toError (/vagrant/node_modules/superagent/lib/node/response.js:94:15)
          at ResponseBase._setStatusProperties (/vagrant/node_modules/superagent/lib/response-base.js:123:16)
          at new Response (/vagrant/node_modules/superagent/lib/node/response.js:41:8)
          at Request._emitResponse (/vagrant/node_modules/superagent/lib/node/index.js:739:20)
          at IncomingMessage.parser (/vagrant/node_modules/superagent/lib/node/index.js:903:38)
          at emitNone (events.js:91:20)
          at IncomingMessage.emit (events.js:185:7)
          at endReadableNT (_stream_readable.js:974:12)
          at _combinedTickCallback (internal/process/next_tick.js:80:11)
          at process._tickCallback (internal/process/next_tick.js:104:9)
        status: 401,
        text: '',
        method: 'GET',
        path: '/sts' },
     accepted: false,
     noContent: false,
     badRequest: false,
     unauthorized: true,
     notAcceptable: false,
     forbidden: false,
     notFound: false,
     type: '',
     links: {},
     setEncoding: [Function: bound ],
     redirects: [] } }

Using expect and should you can test as below:

describe('Testing https responses', () => {

    it("user info", async (done) => {

        .... request here...
        .catch((err) => {
          err.response.should.have.status(404);
          err.response.body.should.have.property('error');
          err.response.body.error.should.eql('User could not be found');

          done()
        });
    })

    it('testing using expect', (done) => {
       request.get('http://localhost:8000', function (err, res, body) {
           expect(res.statusCode).to.equal(400);
           expect(res).to.have.property('body');
           expect(res.body).to.equal('wrong header');
           done();
       });
    });
})

These tests are asynchronous, so they need the promise to be solved at the end with done()

Edit - Added once more example

.property(name[, val[, msg]])

Asserts that the target has a property with the given key name.

 expect({a: 1}).to.have.property('a'); 

Here three links that can be helpful:

You could use try-catch and handle errors =)

it("user info", async () => {

  try{
    let accessToken = 'dfsf;
    const result = await authConnectors.getUser(accessToken);
  } catch(e) {
    // check error
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM