我正在尝试编写一个简单的单元测试。我只需要测试我的函数是否被调用。在我的服务中,我有一个简单的方法,可以调用另一个方法,如下所示
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() {}” block 是我的问题。我在控制台中得到“预期 spy getNewestNotifications 已被调用。”。总的来说,我对单元测试非常陌生我完全不知道为什么我会看到这个,我只是想测试该方法是否确实被调用。有什么帮助吗?
最佳答案
我相信您想要断言每当调用 svc.getNewestNotifications
时都会调用 getNewNotifications
。
为了有效地测试这一点,您需要将 getNewNotifications
定义为 svc
对象的方法,以便在您的测试中可用:
svc.getNewNotifications = function getNewNotifications(user) {
// method definition
};
您应该更新对 svc.getNewestNOtifications
的调用:
svc.getNewestNotifications = function getNewestNotifications() {
svc.getNewNotifications(username);
};
在您的测试中,您为 getNewNotifications
方法创建一个 spy 。然后,您调用 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();
});
});
关于javascript - Jasmine 单元测试的方法称为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36227882/