I have a Service - personService - in my Angular application that has two methods getEverybody and getPersonById. I can replace a method in my service using sinon stub like this:
var everybody = [...];
serviceMock= sinon.stub(personService, "getEverybody").returns(everybody);
How do I write if I want to replace both methods? This does not seem to work:
var everybody = [...];
var aPerson = {...};
serviceMock= sinon.stub(personService, "getEverybody").returns(everybody);
serviceMock= sinon.stub(personService, "getPersonById").returns(aPerson);
The syntax
var stub = sinon.stub(object, "method");
returns a stub for the actual method and not the whole object. You should write
getEverybodyStub = sinon.stub(personService, "getEverybody").returns(everybody);
getPersonByIdStub = sinon.stub(personService, "getPersonById").returns(aPerson);
and then you can write tests like this
describe('PersonService', function(){
var personSrvc;
beforeEach(inject(function (PersonService) {
personSrvc= PersonService;
}));
it('should return all persons', function(){
var everybody = [{name:'aaa'}, {name:'bbb'}];
var getEverybodyStub = sinon.stub(personSrvc,"getEverybody").returns(everybody);
var allPersons = personSrvc.getEverybody();
expect(allPersons ).toEqual(everybody );
expect(getEverybodyStub.called).toBe(true);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With