javascript - Jasmine 单元测试的方法称为

标签 javascript angularjs unit-testing karma-jasmine

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

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/

相关文章:

javascript - 在点击的位置创建一个元素?

javascript - Vuex store this.$store 在 Vue.js 组件中未定义

javascript - Angularjs $rootScope 解析有时不在模板中更新

android - 使用异步任务测试 Android Activity

php - 如何使用 PHPUnit 测试此方法调用?

cocoa - OSX 应用程序的 TDD

javascript - 传递 while 循环内部的输入类型标记的值,其中 while 循环位于 php 内部

javascript - 如何禁用 jsTree 上的热键(arrowKeys)?

angularjs - 如何确定 Angularjs 工厂服务的范围以将唯一数据返回到特定 Controller ?

javascript - 为什么 res.redirect 实际上没有重定向我?