Node.js Mocha 测试 Restful API 端点和代码覆盖率 [英] Node.js Mocha Testing Restful API Endpoints and Code Coverage

查看:61
本文介绍了Node.js Mocha 测试 Restful API 端点和代码覆盖率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直很喜欢伊斯坦布尔,也尝试过其他 Node.js 覆盖库,但我遇到了一个问题.我几乎所有的单元测试都是对 API 的 HTTP 调用,如下所示:

I've been really enjoying Istanbul and experimenting with other Node.js coverage libraries as well, but I have an issue. Nearly all of my unit tests are HTTP calls to my API like so:

    it('should update the customer', function (done) {
        superagent.put('http://myapp:3000/api/customer')
            .send(updatedData)
            .end(function (res) {
                var customer = res.body;
                expect(res.statusCode).to.equal(200);
                expect(customer.name).to.equal(updatedData.name);
                done();
            });
    });

与实际需要customers.js 文件并直接调用updateCustomer 相反.测试端点对我来说更有意义,因为它不仅测试 updateCustomer,还测试路由、控制器和其他所有相关内容.

As opposed to actually requiring the customers.js file and calling updateCustomer directly. Testing the endpoint makes much more sense to me, as it not only tests updateCustomer, but also the routes, controllers, and everything else involved.

这很好用,但问题是我似乎看不到任何代码覆盖工具识别这些测试的方法.伊斯坦布尔或其他任何东西有什么办法可以识别这些摩卡测试吗?如果不是,那么约定是什么?您如何测试端点并仍然使用代码覆盖工具?

This works fine, but the problem is that I can't seem to see a way for any code coverage tool to recognize these tests. Is there any way for Istanbul or anything else to recognize these Mocha tests? If not, what is the convention? How do you test endpoints and still use code coverage tools?

推荐答案

问题是你使用的是 superagent,而你应该使用 supertest 来编写单元测试.如果您使用 supertest,伊斯坦布尔将正确跟踪代码覆盖率.

The issue is that you're using superagent, whereas you should be using supertest to write unit tests. If you use supertest, istanbul will correctly track code coverage.

一些帮助您入门的示例代码:

Some sample code to get you started:

'use strict';

var chai = require('chai').use(require('chai-as-promised'));
var expect = chai.expect;
var config = require('../../config/config');
var request = require('supertest');

var app = require('../../config/express')();

describe('Test API', function () {
  describe('test()', function() {
    it('should test', function(done) {
      request(app)
        .get('/test')
        .query({test: 123})
        .expect('Content-Type', /json/)
        .expect(200)
        .end(function(err, res){
          expect(err).to.equal(null);
          expect(res.body).to.equal('whatever');
          done();
        });
    });

    it('should return 400', function(done) {
      request(app)
        .get('/test/error')
        .query({})
        .expect('Content-Type', /json/)
        .expect(400, done);
    });
  });
});

这篇关于Node.js Mocha 测试 Restful API 端点和代码覆盖率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆