Nodejs / Express API的简单Mocha / Chai测试

时间:2016-05-23 23:19:41

标签: node.js api testing mocha chai

我正在尝试为我的API构建测试集,该测试集是使用nodejs / express与mocha / chai一起开发的。基本上,索引返回一个我知道它正常工作的简单字符串,因为我可以在浏览器上看到:

router.get('/', function(req, res, next) {
    res.send('Hello World from Eclipse');
});

然后我按照tutorial来构建此测试:

var supertest = require("supertest");
var should = require("should");

// This agent refers to PORT where program is runninng.

var server = supertest.agent("http://localhost:5000");

// UNIT test begin

describe("SAMPLE unit test",function(){

  // #1 should return home page

  it("should return home page",function(done){

    // calling home page api
    server
    .get("/")
    .expect("Content-type",/json/)
    .expect(200) // THis is HTTP response
    .end(function(err,res){
      // HTTP status should be 200
      res.status.should.equal(200);
      // Error key should be false.
      res.body.error.should.equal(false);
      done();
    });
  });

});

我可以在我的服务器的日志中看到该地址已被调用,但是,测试总是说它无法读取属性'应该'未定义的,在我所拥有的行#res ;status.should.equal(200);'。可能是因为' res'未定义。换句话说,API没有答案。

我在这里遗漏了什么吗?我运行没有参数的摩卡......

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

var expect = require('chai').expect;
var request = require('supertest');
var uri = 'your url';

describe('Profile',function(){

    it('Should return a users profile',function(done){
        request
            .get(uri + '/api/1.0/profile')
            .query({app_id:'12345'})
            .end(function(err,res){

                var body = res.body;

                expect(body.first_name).to.equal('Bob');
                expect(body.last_name).to.equal('Smith');
                done()
            });
    });
});

确保包含正确的要求。

答案 1 :(得分:0)

您应该检查.end()中的错误:

.end(function(err, res) {
  if (err) return done(err);
  ...
});

测试用例期望内容类型与/json/不匹配,因此它应该被设置(并且res将因此而未定义。)

相关问题