Reputation: 675
I have a model stores data into db then calls another store method by passing the id just created
//db.Poll.store method
store: function (opt, db, callback) {
var pollData = {
question: opt.data.question
};
db.Poll.create(pollData).success(function (poll) {
opt.data.PollId = poll.id;
models.PollOption.store(opt, db, callback);
}).error(function(error) {
callback(error, null);
});
}
I just want to have a unit test to make sure a valid opt.data.PollId is passed to models.PollOption.store() method and I don't want to check if models.PollOption.store() behaviour correctly or not, so I mocked/overwritten the models.PollOption.store method. my unit test is like this below
describe('Method store', function () {
it('should be able to create a poll and pass poll.id to pollOption.store', function (done) {
var opt = {
data: {
question: "Do you love nodejs?"
}
};
var temp = db.PollOption.store;
//mock function
db.PollOption.store = function (opt, db, callback) {
expect(opt.data.PollId).not.to.be.empty
//restore to what it was before
db.PollOption.store = temp;
callback();
};
db.Poll.store(opt, db, done);
});
});
Can I achieve this by using sinon.js , stub db.PollOption.store method?
Upvotes: 0
Views: 1516
Reputation: 3665
i used another test framework, and since i dont have your full code, so here is an example of how to use sinon.spy
basically, the eq(1, opt) means expect(opt).equal.to(1)
var method = { store : function(a){
return a+1
}}
tests({
'should be able to create a poll and pass poll.id to pollOption.store': function () {
sinon.spy(method, "store") // create spy
method.store({opt:1}) // call your function
var spyCall = method.store.getCall(0) // sinon spy API .getCall(0)
// i assume this is the [objects]
// created by the spy on calling method()
eq(1, spyCall.args[0].opt) // your expect()
}
});
Upvotes: 1