Replacing multiple methods in a sinus plug

I have a Service - personService - in my Angular app 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 work:

var everybody = [...];
var aPerson = {...};
serviceMock= sinon.stub(personService, "getEverybody").returns(everybody);
serviceMock= sinon.stub(personService, "getPersonById").returns(aPerson);

      

+3


source to share


1 answer


Syntax

var stub = sinon.stub(object, "method");

      

returns a stub for the actual method, not the entire object. You have to 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);
  });
});

      

+10


source







All Articles