Home > database >  NodeJS Chai Mocha response undefined
NodeJS Chai Mocha response undefined

Time:02-17

I create my test code using typescript and run my test using mocha (mocha --timeout 10000)

The following is my code:

import chai from 'chai';
import chai_http from 'chai-http';

chai.use(chai_http);

describe('upload', () => {
    beforeEach((done) => {
        done();
    });
    describe('/POST upload', () => {
        it('it should not POST a book without pages field', (done) => {
            let book = {
                title: "Test"
            }
        chai.request('http://192.55.55.19:3000')
            .post('/upload')
            .set('Content-Type', 'application/json')
            .send(book)
            .end((err, res) => {
                console.log(`\ntesting3: ${JSON.stringify(res.status)}`);
                res.should.have.status(200);
                done();
            });
        });
    });
});

The error that I got: enter image description here

Clearly, res.status exist.

Why res.should.have.status produce the undefined error?

Actually, I tried other things such as should.have.property nad I got undefined as well.

Thanks in advance

CodePudding user response:

From the assertion styles#should, Chai extends each object with a should property after calling chai.should().

Which means chai will add should property to Object.prototype after calling chai.should().

The should interface extends Object.prototype to provide a single getter as the starting point for your language assertions.

E.g.

const chai = require('chai');
const chaiHttp = require('chai-http');

chai.use(chaiHttp);
chai.should();

describe('71144510', () => {
  it('should pass', () => {
    const res = { status: 200 };
    res.should.have.status(200);
  });
});
  • Related