meenu
meenu

Reputation: 11

spying function inside a function in a service, in controller test using jasmine

let the service be

function testService(){

  function test(){
        return{
              find:find,
              save:save
        };
        function find(){
              //return a promise
        }
        function save(){
              //some code
        }
  }

  return {test:test};

}

let the controller be

function TestController(testService){
  var ctrl=this;
  ctrl.first=first;

  function first(){
          testService.test().find().then(function(response){});
  }

}

how can i mock the the service call in the 'first' function in controller using jasmine

Upvotes: 1

Views: 2066

Answers (2)

meenu
meenu

Reputation: 11

spyOn(testService, 'test').and.callFake(function () {
        return { find: function () {
                return {
                    then: function (callback) {
                        return callback({ 'status': 3 }); }
                };
            }
        };

    });

ctrl.first(); expect(testService.test).toHaveBeenCalled();

i used this method and found working

Upvotes: 0

Phil
Phil

Reputation: 165069

Something like this...

setup

const testSpy = jasmine.createSpyObj('testService.test', ['find', 'save'])
const testServiceSpy = jasmine.createSpyObj('testService', ['test'])
const reponse = {
    status: 200
}
testServiceSpy.test.and.returnValue(testSpy)
testSpy.find.and.returnValue(Promise.resolve(response))

and in your test

const testController = new TestController(testServiceSpy)
testController.first()
expect(testServiceSpy.test).toHaveBeenCalled()
expect(test.find).toHaveBeenCalled()

Upvotes: 2

Related Questions