简体   繁体   中英

how to mock an alert in unit testing of angular

I am trying to mock the alert used in my application

Here is my factory code

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

I tried to write the mock test for this alert as

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

});

But I get this error whenver I try running jasmine test

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

You can simply mock the function. I have choosen to use $window instead. I removed the config since I wasn't sure where you were getting this. And I removed the '/n' from the result, since it was messing with the compare. But this is the way to go:

angular.module('MyApp', [])

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

And the test:

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

You can see the result in this plunkr .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM