【问题标题】:NodeJS Chai Mocha response undefinedNodeJS Chai Mocha 响应未定义
【发布时间】:2022-02-17 11:26:36
【问题描述】:

我使用 typescript 创建我的测试代码并使用 mocha (mocha --timeout 10000) 运行我的测试

以下是我的代码:

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();
            });
        });
    });
});

我得到的错误:

很明显,res.status 存在。

为什么 res.should.have.status 会产生未定义的错误?

实际上,我尝试了其他东西,例如 should.have.property nad 我也未定义。

提前致谢

【问题讨论】:

    标签: node.js unit-testing mocha.js chai chai-http


    【解决方案1】:

    从assertion styles#should,Chai 在调用chai.should() 后使用should 属性扩展每个对象。

    这意味着 chai 将在调用 chai.should() 后将 should 属性添加到 Object.prototype。

    should 接口扩展了Object.prototype 以提供单个 getter 作为语言断言的起点。

    例如

    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);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      相关资源
      最近更新 更多