如何使用sinon使用req和res参数模拟函数?

时间:2017-09-20 10:15:47

标签: node.js sinon

我想在sinon上使用模拟和存根传递一些测试。 controler.js:

const User = require('./models/user');
module.exports.userRead = function userRead(req, res) {
 User
 .query()
 .then(users => {
    res.render('results', {data: users});
  })
 .catch((err) => {
    res.render('error');
 });

user.test.js:

const sinon = require('sinon');
const controller = require('../controler');
const Provider  = require('../provider');

describe('Testing userRead', () => {
   const appStub = sinon.stub(Provider,'query');
   test('should returns users', () => {
       controler.userRead(req, res);

       appStub.restore();
       appStub.verify();
   });
});

测试无法通过,我收到了这个错误:

ReferenceError: req is not defined

我该如何解决?

1 个答案:

答案 0 :(得分:2)

在您的代码中,没有任何名为req

的内容

在您的特定实例中,只需传入{}(空对象),因为您的控制器尚未使用req

执行任何操作
const sinon = require('sinon');
const controller = require('../controler');
const Provider  = require('../provider');

describe('Testing userRead', () => {
   const appStub = sinon.stub(Provider,'query');
   test('should returns users', () => {
       controler.userRead({}, res);

       appStub.restore();
       appStub.verify();
   });
});

另一种(更好的)替代方法是使用https://github.com/howardabrams/node-mocks-http

const sinon = require('sinon');
const httpMocks = require('node-mocks-http');
const controller = require('../controler');
const Provider  = require('../provider');

describe('Testing userRead', () => {
   const appStub = sinon.stub(Provider,'query');
   const req = httpMocks.createRequest();
   //can setup req here

   test('should returns users', () => {
       controler.userRead(req, res);

       appStub.restore();
       appStub.verify();
   });
});