茉莉花单元测试被称为

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() {}”块。我在控制台中得到 "Expected spy getNewestNotifications to have been called."。我对一般的单元测试很陌生,我我完全不知道为什么我会看到这个我只是想测试该方法是否确实被调用了。有什么帮助吗?

我相信您想断言每当调用 svc.getNewestNotifications 时都会调用 getNewNotifications

为了有效地测试它,您需要将 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();
  });
});