繁体   English   中英

茉莉花单元测试被称为方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM