【问题标题】:What type of spy to use for testing什么类型的间谍用于测试
【发布时间】:2016-07-06 17:35:07
【问题描述】:

我知道当您使用 spyOn 时,您可以使用不同的形式,例如 .and.callFake.andCallThrough。我不确定我要测试的这段代码需要哪一个...

  var lastPage = $cookies.get("ptLastPage");
      if (typeof lastPage !== "undefined") {
        $location.path(lastPage);
      } else {
        $location.path('/home'); //TRYING TO TEST THIS ELSE STATEMENT
      }
    }

这是我的一些测试代码:

describe('Spies on cookie.get', function() {
    beforeEach(inject(function() {
      spyOn(cookies, 'get').and.callFake(function() {
        return undefined;
      });
    }));
    it("should work plz", function() {
      cookies.get();
      expect(location.path()).toBe('/home');
      expect(cookies.get).toHaveBeenCalled();
      expect(cookies.get).toHaveBeenCalledWith();
    });
  });

我尝试了很多不同的方法,但我正在尝试测试else 语句。因此我需要制作cookies.get == undefined。 每次我尝试这样做时,都会收到此错误:

Expected '' to be '/home'.

cookies.get() 等于undefined 时,location.path() 的值永远不会改变。我认为我错误地使用了 spyOn?

跟进我的模拟值:

beforeEach(inject(
    function(_$location_, _$route_, _$rootScope_, _$cookies_) {
      location = _$location_;
      route = _$route_;
      rootScope = _$rootScope_;
      cookies = _$cookies_;
    }));

功能跟进:

angular.module('buildingServicesApp', [
   //data
  .config(function($routeProvider) {
    //stuff
  .run(function($rootScope, $location, $http, $cookies) 

这些函数上没有名字,因此我该如何称呼cookies.get

【问题讨论】:

  • 什么是cookies?它从哪里来的?如果这应该模拟$cookies,那就错了。 $cookies 没有注入,cookies 不是$cookies
  • 有一个捷径:spyOn(cookies, 'get').and.returnValue(undefined);
  • 我添加了一个编辑来帮助澄清我的模拟。不确定这是否是您的意思,但我的代码中确实有这些模拟,只是没有显示。

标签: angularjs unit-testing jasmine


【解决方案1】:

现在,您正在测试location.path() 函数是否按设计工作。我想说你应该把测试留给 AngularJS 团队:)。相反,请验证该函数是否被正确调用:

  describe('Spies on cookie.get', function() {
    beforeEach((function() { // removed inject here, since you're not injecting anything
      spyOn(cookies, 'get').and.returnValue(undefined); // As @Thomas noted in the comments
      spyOn(location, 'path');
    }));
    it("should work plz", function() {
      // cookies.get(); replace with call to the function/code which calls cookies.get()
      expect(location.path).toHaveBeenCalledWith('/home');
    });
  });

请注意,您不应该测试您的测试是否模拟 cookies.get,您应该测试调用问题中第一段代码的任何函数是否在做正确的事情。

【讨论】:

  • 嘿,谢谢老兄的精彩回复。不幸的是,我调用函数/代码的问题是没有?这是我的问题之一......我将添加另一个编辑并解释。
  • 你可以看看这个问题:stackoverflow.com/q/24948577/215552。恐怕我对控制器和指令之外的角度测试知之甚少。
猜你喜欢
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-18
相关资源
最近更新 更多