Node.js Sinon.js与猫鼬和蓝知更鸟
我有一个助手函数,它使用promisified Mongoose查询。我对使用Sinon.js进行测试相当陌生,不知道如何测试使用蓝鸟承诺的猫鼬 以下是我的功能:Node.js Sinon.js与猫鼬和蓝知更鸟,node.js,mongoose,mocha.js,bluebird,sinon,Node.js,Mongoose,Mocha.js,Bluebird,Sinon,我有一个助手函数,它使用promisified Mongoose查询。我对使用Sinon.js进行测试相当陌生,不知道如何测试使用蓝鸟承诺的猫鼬 以下是我的功能: module.exports = function addParticipant(session, user) { Session.Promise = Promise; return Session .findById(session._id) .populate('location') .populate('
module.exports = function addParticipant(session, user) {
Session.Promise = Promise;
return Session
.findById(session._id)
.populate('location')
.populate('participants)
.then((session) => {
const participant = new Participant({
user: user._id,
session: session.id
});
return participant.save((err) => {
if (err) {
Promise.reject(err);
}
session.participants.push(participant);
session.save((err) => {
if (err) {
Promise.reject(err);
}
notifications.notifyLearner(notifications.LEARNER_REGISTERED, {
session,
user
});
Promise.resolve(participant);
});
});
});
};
我想测试是否调用了学生通知,这就是我所拥有的,但我不知道如何模拟我承诺链的then
部分
describe('helpers', () => {
describe('addParticipant', () => {
let SessionMock;
beforeEach(() => {
SessionMock = {
populate: sinon.spy(() => SessionMock)
};
sinon.stub(Session, 'findById', () => SessionMock);
sinon.stub(Session.prototype, 'save', (cb) => cb(null));
sinon.stub(Participant.prototype, 'save', (cb) => cb(null));
sinon.stub(notifications, 'notifyLearner');
});
afterEach(() => {
Session.findById.restore();
Session.prototype.save.restore();
Participant.prototype.save.restore();
notifications.notifyLearner.restore();
});
describe('add participant to session', () => {
let testSession;
let testUser;
let addParticipantPromise;
beforeEach(() => {
testUser = new User({
_id: new mongoose.Types.ObjectId
});
testSession = new Session({
_id: new mongoose.Types.ObjectId,
participants: []
});
// Probably not the best way to do this.
SessionMock.then = sinon.spy((cb) => {
cb(testSession);
});
addParticipantPromise = addParticipant(testSession, testUser);
});
it.only('should notify Learner', () => {
return addParticipantPromise.then(() => {
notifications.notifyLearner.should.be.called();
});
});
});
});
});
我可以将我的testSession
传递到然后
函数中,但我的承诺无法解决任何问题
我如何测试这个?什么是正确的间谍/存根/嘲弄承诺的方式
谢谢