简体   繁体   中英

Unit Testing Factories Jasmine-Sinon

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM