[英]how to mock an alert in unit testing of angular
我試圖模擬我的應用程序中使用的警報
這是我的工廠代碼
app.factory('Handler', ['config', '$location',function (config, $location){
return {
log: function (message, data) {
if (config.DEBUG) {
alert('Alert Message (' + message + "):\n" + JSON.stringify(data));
}
}
}
}]);
我嘗試將此警報的模擬測試編寫為
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" ');
});
});
但是當我嘗試運行茉莉花測試時,我收到此錯誤
Expected spy unknown to have been called with [ 'Alert Message (A): "B" ' ] but it was never called.
你可以簡單地模擬這個功能。 我選擇使用$ 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));
}
}
}]);
而且測試:
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"' );
});
});
你可以在這個plunkr中看到結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.