Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing multiple methods in sinon stub

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);
like image 934
Dalby Modo Avatar asked Aug 06 '14 09:08

Dalby Modo


1 Answers

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);
  });
});
like image 171
Edminsson Avatar answered Sep 30 '22 17:09

Edminsson