[英]jasmine unit testing was method called
我正在嘗試編寫一個簡單的單元測試。 我只需要測試我的函數是否被調用。 在我的服務中,我有一個簡單的方法,可以像這樣調用另一種方法
svc.getNewestNotifications = function getNewestNotifications() {
getNewNotifications(username);
};
在我的測試中:
describe('notification service tests', function () {
var $rootScope, $http, $q, notificationSvc, $httpBackend;
beforeEach(module('myApp'));
beforeEach(inject(function(_$rootScope_,_$http_,_$httpBackend_,_$q_,_$sce_,_notificationsFeedService_){
$rootScope = _$rootScope_;
$httpBackend = _$httpBackend_;
$http = _$http_;
$q = _$q_;
notificationSvc = _notificationsFeedService_;
_scope_ = $rootScope.$new();
$scope = _scope_;
$httpBackend.whenGET(/\.html$/).respond('');
}));
describe("getNewestNotifications test", function() {
it('calls the getNewestNotifications when scroll to top', function() {
spyOn(notificationSvc, 'getNewestNotifications').and.callThrough();
expect(notificationSvc.getNewestNotifications).toHaveBeenCalled();
});
});
}
它的“ describe(”getNewestNotifications test”, function() {} “塊是我的問題。我在控制台中收到“預期的間諜 getNewestNotifications 已被調用。”我對單元測試很陌生,我是完全不知道為什么我看到這個我只是想測試該方法確實被調用了。有幫助嗎?
我相信您想斷言每當調用getNewNotifications
都會調用svc.getNewestNotifications
。
為了有效地測試這一點,您需要將getNewNotifications
定義為svc
對象的方法,以便它在您的測試中可用:
svc.getNewNotifications = function getNewNotifications(user) {
// method definition
};
您應該更新對svc.getNewestNOtifications
的調用:
svc.getNewestNotifications = function getNewestNotifications() {
svc.getNewNotifications(username);
};
在您的測試中,您為getNewNotifications
方法創建了一個間諜。 然后調用getNewestNotifications
方法並斷言getNewNotifications
被調用:
describe("getNewestNotifications test", function() {
it('calls the getNewestNotifications when scroll to top', function() {
// set a spy on the 'getNewNotifications' method
spyOn(notificationSvc, 'getNewNotifications').and.callThrough();
// call the 'getNewestNotifications'. If the function works as it should, 'getNewNotifications' should have been called.
notificationSvc.getNewestNotifications();
// assert that 'getNewNotifications' was called.
expect(notificationSvc.getNewNotifications).toHaveBeenCalled();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.