【问题标题】:jasmine unit testing was method called茉莉花单元测试被称为方法
【发布时间】:2016-07-13 16:16:46
【问题描述】:

我正在尝试编写一个简单的单元测试。我只需要测试我的函数是否被调用。在我的服务中,我有一个简单的方法可以调用另一个方法,像这样

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 这个方法被调用了
  • @PankajParkar 我不明白你的评论
  • it 部分你应该调用一些东西,现在你只有期望。为什么应该调用 notificationSvc.getNewestNotifications - 由什么调用?
  • @KrzysztofSafjanowski 这是一个非常好的问题。我想这就是我如此困惑的原因。这对我来说没有任何意义。我不知道这怎么可能起作用。 Javascript 是有道理的,但是我完全迷失了这个单元测试的东西。我想我认为测试会知道服务应该调用该方法。我不知道。无论如何谢谢。

标签: javascript angularjs unit-testing karma-jasmine


【解决方案1】:

我相信您想断言,无论何时调用 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();
  });
});  

【讨论】:

  • 我喜欢你的想法,但是 getNewNotifications() 是一个私有函数,声明如下:` function getNewNotifications() { // do stuff } ` 如果是这种情况,我该怎么做?
猜你喜欢
  • 1970-01-01
  • 2017-09-27
  • 1970-01-01
  • 2022-01-23
  • 2020-11-25
  • 1970-01-01
  • 2020-08-19
  • 2015-10-01
相关资源
最近更新 更多