node.js - 使用 express、node.js 构建的 restful api 的单元测试日志记录(使用 mocha、supertest 和 chai)

标签 node.js mocha.js supertest

我用 mocha、chai 和 supertest 编写了一个简单的单元测试。

describe('controller.CWEManagementAPI', function () {
it('should be able to say hello', function() { 
    var request = require('supertest')
    , express = require('express');

    var app = express();

    app.get('/user', function(req, res){
        res.send(201, { name: 'tobi' });
    });

    request(app)
    .get('/user')
    .set('Accept', 'application/json')
    .expect(200)
    .end(function(err, res){
        if (err) return done(err);
        console.log('test');
        assert.equal( res.body.name, 'tobi');
        done()
    });
});
});

但问题是:console.log('test') 没有执行。 所以我认为 assert.equal( res.body.name, 'tobi'); 也没有执行。 所以我在没有单元测试的情况下编写代码,例如:

var request = require('supertest')
, express = require('express');

var app = express();

app.get('/user', function(req, res){
res.send(201, { name: 'tobi' });
});

request(app)
   .get('/user')
   .expect('Content-Type', /json/)
   .expect('Content-Length', '20')
   .expect(201)
   .end(function(err, res){ 
    if (err) throw err;
    console.log(res.body.name);
    console.log('done');
    process.exit();
   });

console.log() 全部执行。所以我不知道为什么第一个代码不能显示日志信息。

最佳答案

您尝试运行的是使用 mocha 的异步测试。因此,测试用例应该收到一个回调参数,以便在完成其操作后调用。

你在最后调用了 done() 但还没有收到它作为参数。

改变

it('should be able to say hello', function() {
}

it('should be able to say hello', function(done) {
}

关于node.js - 使用 express、node.js 构建的 restful api 的单元测试日志记录(使用 mocha、supertest 和 chai),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14333491/

相关文章:

node.js - 类型错误 : Cannot read property 'connect' of undefined

node.js - 单独运行 Mocha 测试

node.js - 如何使用nodejs和mocha模拟另一个lambda函数内的aws lambda函数调用

typescript - webdriverio 5.7.5 出现错误 $(...).setValue 不是函数

javascript - Node : Mocha TDD sending Array in body

node.js - Websocket - 等待 http 请求回调在下一个推送事件之前执行

javascript - mypromise.then 内函数的返回值

mysql - NodeJS在启用集群的情况下缓存mysql数据

testing - 为什么 Diaspora 应用程序中的这个测试没有失败?

node.js - supertest 无法解析状态码 400