Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了angularjs – createSpy如何在Angular Jasmine中工作?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我做了一个工厂的简单演示,我试图用茉莉花测试这个.我能够运行测试,但我正在使用spyOn方法.我宁愿使用jasmine.createSpy或jasmine.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');
  });
})

更新

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()
})

解决方法

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

这就是你应该测试的:

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);
  });
});

此外,您的服务不是工厂.工厂是用于创建事物的对象.您的服务不会创建任何内容.它使用工厂功能在角度模块中注册.但服务本身不是工厂.

大佬总结

以上是大佬教程为你收集整理的angularjs – createSpy如何在Angular Jasmine中工作?全部内容,希望文章能够帮你解决angularjs – createSpy如何在Angular Jasmine中工作?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: