我想在sinon.js上使用模拟传递测试。 app.js:
const express = require('express');
const route = require('./server/routes/index');
const app = express();
app.use('/', route);
index.js:
const router = require('express').Router();
const ctrlUsers = require('../controllers/users');
router.get('/users', ctrlUsers.UsersRead);
users.js:
const User = require('../models/user');
module.exports.UsersRead = function UsersRead(req, res) {
User
.query()
.then((user) => {
res.render('results');
})
.catch((err) => {
res.render('error');
});
};
user.test.js:
const app = require('../app');
const sinon = require('sinon');
describe('Get /users', () => {
const appMock = sinon.mock(app);
test('status of get', () => {
appMock.expects('get').once().withArgs('/users').returns(0);
appMock.restore();
appMock.verify();
});
});
我运行测试文件,但测试失败,我收到了这个错误:
ExpectationError: Expected get(/providers[, ...]) once (never called)
at Object.fail (node_modules/sinon/lib/sinon/mock-expectation.js:281:25)
at Object.verify (node_modules/sinon/lib/sinon/mock.js:108:29)
at Object.test (__tests__/usersRoutes.test.js:11:13)
at Promise (<anonymous>)
at <anonymous>
我该如何解决?
答案 0 :(得分:0)
你应该调用app来嘲笑它。创建mock之后,将app.get('/users')
添加到代码中:
const app = require('../app');
const sinon = require('sinon');
describe('Get /users', () => {
const appMock = sinon.mock(app);
test('status of get', () => {
appMock.expects('get').once().withArgs('/users').returns(0);
app.get('/users');
appMock.restore();
appMock.verify();
});
});
有关详细信息,请查看Sinon.js