如何对AngularJS服务/工厂进行单元测试

How to unit test an AngularJS service / factory

本文关键字:工厂 单元测试 服务 AngularJS      更新时间:2023-09-26

我已经使用AngularJS开发了一段时间,我所写的东西可以工作,但是我知道我已经到了想在我的AngularJS代码上运行单元测试的时候了。

我已经创建了一个非常简单的服务,将注入一个样式表到页面,参见下面的示例代码:

var OfficeSuiteStylesheetInjectorModule = angular.module('OfficeSuiteStylesheetInjectorModule', []);
OfficeSuiteStylesheetInjectorModule.factory('stylesheetInjectorService', ['$q', function($q) {
    // Returns the service itself.
    return {
        inject: function(id, uri) {
            var deferred = $q.defer();
            // Embed the stylesheet into the page, but only when it's non-existing.
            if (!angular.element('#' + id).length) {
                    var link = StylesheetFactory.Create(id, uri);
                    {
                        link.onload = deferred.resolve;
                        angular.element('head').append(link);
                    }
                    return deferred.promise;
                }
        }
    }
}]);

这不是一个大的服务,它只是依赖于$q的承诺,所以我可以运行额外的逻辑,当样式表已经嵌入到页面。

现在,我正在使用Jasmine(我对此很陌生)来测试我的JavaScript代码,我想测试这个模块。

I have a skeleton:

// Tests for the angular 'StylesheetInjectorService'.
describe('StylesheetInjectorService', function() {
    var stylesheetInjectorService = {};
    // This code is executed before every test.
    beforeEach(function() {
        // Tells jamine that the module we're working on is the 'OfficeSuiteStylesheetInjectorModule'.
        angular.module('OfficeSuiteStylesheetInjectorModule');
    });
    // Ensures that it injects a stylesheet element into the page.
    it('Should inject a stylesheet element into the page.', function() {
        // How to test here that the stylesheet is injected?
    });
  });
});

我如何在页面中注入服务并确保样式表被加载?

编辑:加载服务现在工作:

beforeEach(module('OfficeSuiteStylesheetInjectorModule'));
// This code is executed before every test.
beforeEach(function() {
    // Inject the required dependencies into the page.
    inject(function($injector) {
        stylesheetInjectorService = $injector.get('stylesheetInjectorService');
    });
});

同样的问题仍然是开放的。如何测试页面中是否嵌入了样式表?

任何帮助都非常感谢。

亲切的问候

要编写样式表附件到angular.element('head')的规范,我将稍微改变一下逻辑,将其附加到$document.head

如果您想要这样做,我建议您将您的服务更改为directive,看看如何注入脚本元素,正在操纵DOM。这样你就一举两得了,因为你需要注入$compile来测试你的指令(这将使你能够$编译一个自定义的head元素来启动)。但现在这有点"过头了"。

实现:

if (!angular.element('#' + id).length) {
  var link = StylesheetFactory.Create(id, uri);
    link.onload = deferred.resolve;
    $document.head.append(link);
    return deferred.promise;
  }
}

beforeEach:

/**
 * Sorry, this was previously $location which was just 
 * such a silly mistake.
 */
var $timeout; 
beforeEach(function () {
  inject(function ($injector) {
    $timeout = $injector.get('$timeout');
  });
});

:

it('attaches the stylesheet to $document.head', function () {
  styleSheetInjectorService.inject('someId', '/path/to/some/stylesheet');
  $timeout.flush(); // flush promises
  expect(angular.element($document.head).lastChild[0].nodeName).to.eq('LINK');
});

这样的事情应该让你开始运行。请记住,我编写的规范使用了chai#expect样式断言和mocha测试框架。如果要复制粘贴,请编辑适合Jasmine的语法。

我之前就有这个疑问。要将控制器和服务注入到测试中,你需要使用一个叫做Angular mock的工具。这里有一些关于它的官方参考。

我建议您将它与Karma环境一起使用。

这是一个很好的入门教程:

https://www.airpair.com/angularjs/posts/unit-testing-angularjs-applications

另一个是为Ionic框架,但仍然可以适用于你的情况

希望能有所帮助。