简体   繁体   English

单元测试工厂Jasmine-Sinon

[英]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 我写测试,但我不能调用set方法,并已实际设置carnewCar

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. 一种是.car属性将始终为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. 在这里,您使用car初始化它为null。 There will be no reference between them. 他们之间将没有参考。 This will always be null since you never change that property on the object: 由于您永远不会在对象上更改该属性,因此它将始终为null:

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. 但是与此有关,您稍后可能会遇到一些与this相关的问题。 Why are you trying to expose car if you have a getter for it? 如果您有吸气剂,为什么要尝试暴露car

The other thing is that you replace the entire get and set functions with this: 另一件事是,您将整个getset函数替换为:

myService.set = sinon.spy();
myService.get = sinon.spy();

Sinon knows nothing about your original get and set . 兴农什么都不知道关于你的原始getset

You should do it like this: sinon.spy(myService, 'set'); 您应该这样做: sinon.spy(myService, 'set');

So sinon can wrap your function with a spy while preserving it's original behavior. 因此,sinon可以在保留原有功能的同时将其功能与间谍结合起来。 Check Sinon documentation 查看Sinon文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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