如何使用Jasmine监视匿名函数 [英] How to spy on anonymous function using Jasmine

查看:130
本文介绍了如何使用Jasmine监视匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jasmine测试我的角度应用程序,并希望监视一个匿名函数。
使用角度通知服务 https://github.com/cgross/angular-notify,我想知道是否已经调用了通知功能。

I'm using Jasmine to test my angular application and want to spy on an anonymous function. Using angular-notify service https://github.com/cgross/angular-notify, I want to know whether notify function have been called or not.

这是我的控制器:

angular.module('module').controller('MyCtrl', function($scope, MyService, notify) {

  $scope.isValid = function(obj) {
    if (!MyService.isNameValid(obj.name)) {
      notify({ message:'Name not valid', classes: ['alert'] });
      return false;
    }
  }
});

这是我的测试:

'use strict';

describe('Test MyCtrl', function () {
  var scope, $location, createController, controller, notify;

  beforeEach(module('module'));

  beforeEach(inject(function ($rootScope, $controller, _$location_, _notify_) {
    $location = _$location_;
    scope = $rootScope.$new();
    notify = _notify_;

    notify = jasmine.createSpy('spy').andReturn('test');

    createController = function() {
      return $controller('MyCtrl', {
        '$scope': scope
      });
    };
  }));

  it('should call notify', function() {
    spyOn(notify);
    controller = createController();
    scope.isValid('name');
    expect(notify).toHaveBeenCalled();
  });
});

明显的回报:

Error: No method name supplied on 'spyOn(notify)'

因为它应该像spyOn(notify,'method'),但由于它是一个匿名函数,它没有任何方法。

Because it should be something like spyOn(notify, 'method'), but as it's an anonymous function, it doesn't have any method.

感谢您的帮助。

推荐答案

Daniel Smink的回答是正确的,但请注意Jasmine 2.0的语法已经改变。

Daniel Smink's answer is correct, but note that the syntax has changed for Jasmine 2.0.

notify = jasmine.createSpy().and.callFake(function() {
  return false;
});

我还发现如果你只需要一个简单的实现就可以直接返回一个响应

I also found it useful to just directly return a response if you only need a simple implementation

notify = jasmine.createSpy().and.returnValue(false);

这篇关于如何使用Jasmine监视匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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