createSpy如何在Angular + Jasmine中运行? [英] How does the createSpy work in Angular + Jasmine?

查看:97
本文介绍了createSpy如何在Angular + Jasmine中运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I made a simple demo of a factory and I am trying to test this using jasmine. I am able to run the test but I am using the spyOn method. I would rather use jasmine.createSpy or jasmine.createSpyObj to do the same test. Could someone help me to refactor my code so that uses these methods instead in my example?

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


推荐答案

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

As said in the comments, you have absolutely no need for spies to test such a service. If you had to write the documentation for your service: you would say:


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

setValue() allows storing a value. This value can then be retrieved by calling 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);
  });
});

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

Also, your service is not a factory. A factory is an object that is used to create things. Your service doesn't create anything. It is registered in the angular module using a factory function. But the service itself is not a factory.

这篇关于createSpy如何在Angular + Jasmine中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆