[英]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.
我选择使用$ window代替。 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.
我从结果中删除了'/ n',因为它搞乱了比较。 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"' );
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.