繁体   English   中英

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

[英]Unit test logging (use mocha, supertest, and chai) of restful api built with express, node.js

我用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) {
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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