createSpy如何在Angular + Jasmine中运行?

use*_*513 5 jasmine angularjs angularjs-directive angularjs-scope karma-runner

我做了一个工厂的简单演示,我试图用茉莉花测试这个.我能够运行测试,但我正在使用spyOn方法.我宁愿使用jasmine.createSpyjasmine.createSpyObj来做同样的测试.有人可以帮我重构我的代码,以便在我的例子中使用这些方法吗?

http://plnkr.co/edit/zdfYdtWbnQz22nEbl6V8?p=preview

describe('value check',function(){
  var $scope,
  ctrl,
  fac;
  beforeEach(function(){
    module('app');

  });

beforeEach(inject(function($rootScope,$controller,appfactory) {
    $scope = $rootScope.$new();  
     ctrl = $controller('cntrl', {$scope: $scope});
     fac=appfactory;
     spyOn(fac, 'setValue');
     fac.setValue('test abc');
}));


  it('test true value',function(){
    expect(true).toBeTruthy()
  })

   it('check message value',function(){
    expect($scope.message).toEqual(fac.getValue())
  })

   it("tracks that the spy was called", function() {
    expect(fac.setValue).toHaveBeenCalled();
  });

  it("tracks all the arguments of its calls", function() {
    expect(fac.setValue).toHaveBeenCalledWith('test abc');
  });
})
Run Code Online (Sandbox Code Playgroud)

更新

angular.module('app',[]).factory('appfactory',function(){
  var data;
  var obj={};
  obj.getValue=getValue;
  obj.setValue=setValue;

  return obj;

  function getValue(){
   return data; 
  }

  function setValue(datavalue){
    data=datavalue;
  }

}).controller('cntrl',function($scope,appfactory){
  appfactory.setValue('test abc');
  $scope.message=appfactory.getValue()
})
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 0

正如评论中所说,你绝对不需要间谍来测试这样的服务。如果您必须为您的服务编写文档:您会说:

setValue()允许存储一个值。然后可以通过调用 来检索该值getValue()

这就是你应该测试的:

describe('appfactory service',function(){
  var appfactory;

  beforeEach(module('app'));

  beforeEach(inject(function(_appfactory_) {
    appfactory = _appfactory_;
  }));

  it('should store a value and give it back',function() {
    var value = 'foo';
    appfactory.setValue(value);
    expect(appfactory.getValue()).toBe(value);
  });
});
Run Code Online (Sandbox Code Playgroud)

另外,您的服务不是工厂。工厂是用于创建事物的对象。你的服务不会创造任何东西。它使用工厂函数注册在 Angular 模块中。但服务本身并不是工厂。