簡體   English   中英

Node.js Mocha測試Restful API端點和代碼覆蓋率

[英]Node.js Mocha Testing Restful API Endpoints and Code Coverage

我一直非常喜歡伊斯坦布爾並嘗試其他Node.js覆蓋庫,但我有一個問題。 幾乎所有的單元測試都是對我的API的HTTP調用,如下所示:

    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 ,還測試路由,控制器和其他所有相關內容。

這很好,但問題是我似乎無法找到任何代碼覆蓋工具識別這些測試的方法。 有沒有辦法讓伊斯坦布爾或其他任何東西認識到這些摩卡測試? 如果沒有,那么慣例是什么? 您如何測試端點並仍然使用代碼覆蓋工具?

問題是你使用superagent ,而你應該使用supertest來編寫單元測試。 如果您使用supertest ,istanbul將正確跟蹤代碼覆蓋率。

一些示例代碼可以幫助您入門:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM