Reputation: 11
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
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
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