0

我正在尝试测试 get 函数:

exports.get = function(req, res) {
  Subscriptions
    .find(req.params.id)
    .success(function(subscription) {
      if (subscription) {
        res.json({message: "Success"}, 200);
      } else {
        res.json({message: "Not found"}, 404);
      }
    })
    .error(function(error) {
        res.json({message: "Internal server error"}, 500);
    });
};

具体来说,我并不关心它是否命中数据库,我只想测试发生成功和错误事件的场景。我使用 sequelize.js 作为我的 orm 来处理数据库。我已经启动并运行了一个测试,但它有点讨厌,超时。有没有更好的方法来做到这一点?这是我到目前为止写的测试:

var express = require('express')
  , sinon = require('sinon')
  , subscription = require('app/controllers/subscriptions')
  , Subscriptions = require('app/models/subscriptions')
  ;

describe('subscription controller', function() {
  beforeEach(function() {
    this.mockResponse = sinon.mock(express.response);
  });

  afterEach(function() {
    this.mockResponse.restore();
  });

  describe('GET /subscriptions/:id', function() {
    it('should return a json response', function(done) {
      var request = {
        params: {
          id: 'identifier'
        }
      };

      var expectedResponse = {
        subscriptions_uri : "/subscription/identifier"
      };

      this.mockResponse
        .expects('json')
        .once()
        .withArgs(expectedResponse);

      subscription.get(request, express.response);
      setTimeout(function() {
        done();
      }, 500);
    });
  });
});
4

1 回答 1

0

我决定使用 supertest 库,这使得测试我的控制器变得异常容易:

var express = require('express')
  , subscription = require('app/controllers/subscriptions')
  , request = require('supertest')
  , app = express()
  ;

describe('subscription controller', function() {
  describe('GET /subscriptions/:id', function() {
    it('should return a json response', function(done) {
      var expectedBody = {
        subscriptions_uri : "/subscription/identifier"
      };

      request(app)
        .get('/subscriptions/identifier')
        .set('Accept', 'application/json')
        .expect('Content-Type', /json/)
        .expect(expectedBody)
        .expect(200, done);
    });
  });
});
于 2013-04-02T15:44:49.077 回答