提问者:小点点

与兴农柴一起测试在具有多个回调的节点JS Express路由中调用了单个回调


我对Node和Sinon比较陌生。这个应用程序是用Express制作的,我使用的是摩卡、柴和Sinon。使用Sinon-cha,我在Express中测试带有多个回调的POST路由,不知道如何检查第二次和后续回调。

我index.js里面的路线是:

var controller = require('./example.controller');
var validator = require('./example.validator');
var router = express.Router();

router.post('/', validator.create, controller.create);

在我的validator.js中是validator.create,它检查提交的参数:

exports.create = function(req, res, next) {
  var valid = true;
  var errorMessages = [];

  if (req.body.name) {
    patt = /[^a-zA-Z0-9 !@#$%^&*()_+\-=\[\]{};':]/g;
    if (patt.test(req.body.name)) {
      valid = false;
      errorMessages.push("Parameter is not alphanumeric");
    }
  }

  if (valid == false) {
    return res.status(400).json(errorMessages);
  }

  next();
}

在我的控制器中。js是控制器。create,用于在数据库中创建条目:

exports.create = function(req, res) {
    return Example.create(req.body)
        .then(baseController.respondWithResult(res, 201))
        .catch(baseController.handleError(res));
}

Sinon Chai在我的index.spec.js中测试:

var proxyquire = require('proxyquire').noPreserveCache();   

var exampleCtrlStub = {
    create: 'exampleCtrl.create',
};

var exampleValidatorStub = {
    create: 'exampleValidator.create'
}

var routerStub = {
    get: sinon.spy(),
    put: sinon.spy(),
    patch: sinon.spy(),
    post: sinon.spy(),
    delete: sinon.spy()
};

var exampleIndex = proxyquire('./index.js', {
    express: {
        Router() {
            return routerStub;
        }
    },
    './example.controller': exampleCtrlStub,
    './example.validator': exampleValidatorStub
});

describe('POST /api/examples', function() {
    it('should route to example.validator.create', function() {
        routerStub.post
            .withArgs('/', 'exampleValidator.create')
            .should.have.been.calledOnce;
    });
});


describe('POST /api/examples', function() {
    it('should route to example.controller.create', function() {
        routerStub.post
            .withArgs('/', 'exampleCtrl.create')
            .should.have.been.called;
    });
});

虽然期望两个测试都通过,但第一个测试(验证器.create)通过,但第二个测试(控制器.create)失败。我无法找到一种方法来测试控制器.create是否被调用。


共1个答案

匿名用户

在第二个测试中,我们不能使用with Args跳过第一个验证器参数。测试失败,因为它正在寻找一个具有此签名的方法,该方法在源代码中不存在。

router.post('/', controller.create);

与Args总是从第一个参数开始,然后是第二个参数,依此类推。因此,解决方案是在测试中包含验证器

routerStub.post
  .withArgs('/', 'exampleValidator.create', 'exampleCtrl.create')
  .should.have.been.called;

参考文献:

    < Li > https://sino njs . org/releases/v 7 . 2 . 3/mocks/# expectationwithargsarg 1-arg 2-

希望它有所帮助