如何在角度单位测试中模拟警报

dee*_*eps 3 javascript unit-testing angularjs

我试图模拟我的应用程序中使用的警报

这是我的工厂代码

 app.factory('Handler', ['config', '$location',function (config, $location){
    return {
        log: function (message, data) {
            if (config.DEBUG) {
                alert('Alert Message (' + message + "):\n" + JSON.stringify(data));
            }
        }
    }
   }]);
Run Code Online (Sandbox Code Playgroud)

我尝试将此警报的模拟测试编写为

 describe("checking  Handler service " , function(){
  var Handler, mock ;
  beforeEach(module("MyApp"));
  beforeEach(function(){
  mock = {alert: jasmine.createSpy()};
  inject(function(_Handler_){
    Handler = _Handler_;
    });
});
it("should check for alert",function(){
    spyOn(Handler, "log");
    Handler.log('A','B');
    expect(mock.alert).toHaveBeenCalledWith('Alert Message (A):\n "B" ');
});
Run Code Online (Sandbox Code Playgroud)

});

但是当我尝试运行茉莉花测试时,我收到此错误

Expected spy unknown to have been called with [ 'Alert Message (A): "B" ' ] but it was never called.
Run Code Online (Sandbox Code Playgroud)

Daa*_*lst 6

你可以简单地模拟这个功能.我选择使用$ window代替.我删除了配置,因为我不知道你在哪里得到这个.我从结果中删除了'/ n',因为它搞乱了比较.但这是要走的路:

angular.module('MyApp', [])

.factory('Handler', ['$location', '$window', function ($location, $window){
    return {
        log: function (message, data) {
           $window.alert('Alert Message (' + message + "): " + JSON.stringify(data));
        }
    }
 }]);
Run Code Online (Sandbox Code Playgroud)

而且测试:

 describe("checking  Handler service " , function(){
    var Handler, _$location_, $window;

    beforeEach(module("MyApp"));

    beforeEach(function($provide) {
       module(function ($provide) {
         $window = { alert: function(message) {

         }};
         spyOn($window, "alert");
         $provide.value('$window', $window);
      });
    });

    beforeEach(inject( function(_Handler_, _$location_) {
       Handler = _Handler_;
       $location = _$location_;

       spyOn(Handler, "log").andCallThrough();

    }));

  it("should check for alert",function(){
      Handler.log('A','B');
      expect(Handler.log).toHaveBeenCalledWith('A', 'B');
      expect($window.alert).toHaveBeenCalledWith( 'Alert Message (A): "B"' );
  });
});
Run Code Online (Sandbox Code Playgroud)

你可以在这个plunkr中看到结果.