Reputation: 1113
I have a factory with a getter and setter
.factory('myService', function() {
var car = null;
return {
car: car,
get: function get() {
return car;
},
set: function set(newCar) {
car = newCar;
}
};
});
I am writing test for it but I cannot call the set
method and have it actually set car
to newCar
myService.set = sinon.spy();
myService.get = sinon.spy()
it('should set car to new car', function () {
var newCar = ['a','b','c'];
expect(myService.car).toEqual(null); //pass
myService.set(newCar);
dump(myService.car); //null
expect(myService.set).toHaveBeenCalledWith(newCar);//pass
expect(myService.get).toHaveReturned(newCar);//fail
});
Any advice on what I am doing wrong here?
Upvotes: 1
Views: 49
Reputation: 9040
There are more problems here.
One is that the .car
property will always be null.
var car = null;
return {
car: car,
get: function get() {
return car;
},
set: function set(newCar) {
car = newCar;
}
};
Here you initialize it with car
which is null. There will be no reference between them. This will always be null since you never change that property on the object:
dump(myService.car); //null
You might do something like:
return {
car: null,
get: function get() {
return this.car;
},
set: function set(newCar) {
this.car = newCar;
}
};
But with this you might run into some this
context issues later. Why are you trying to expose car
if you have a getter for it?
The other thing is that you replace the entire get
and set
functions with this:
myService.set = sinon.spy();
myService.get = sinon.spy();
Sinon knows nothing about your original get
and set
.
You should do it like this:
sinon.spy(myService, 'set');
So sinon can wrap your function with a spy while preserving it's original behavior. Check Sinon documentation
Upvotes: 1