我想在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
我该如何解决?
答案 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();
});
});