【问题标题】:Jasmine: Trying to test an AngularJS factory functionJasmine:尝试测试 AngularJS 工厂函数
【发布时间】:2015-04-27 06:53:48
【问题描述】:

我对 AngularJS 中的测试完全陌生。我已经设置了业力,现在正在尝试在我编写的工厂中测试某个功能。

这是我工厂的一个sn-p:

app.factory('helpersFactory', ['constants', function (constants) {
    return {

        someFunction: function() {
        },

        is24x24Icon: function (iconNum) {
            return ((iconNum >= 10090 && iconNum <= 10125) ;
        }
    };

 }]);

然后我有这个测试:

describe('Factory: helpersFactory', function () {

    beforeEach(module('ppMobi'));

    var fct;
    beforeEach(inject(function ($factory) {
        fct = $factory('helpersFactory');
    }));

    it('should detect iconNum 10090 is a 24 x 24 icon', function () {

        var iconNum = 10090;
        var is24x24Icon = fct.is24x24Icon(iconNum);
        expect(is24x24Icon).toBeTruthy();

    });
});

我从 Karma 收到一条错误消息,告诉我它无法读取未定义的“is24x24icon”。因此我只能假设我的工厂在测试期间没有正确创建。我确实依赖于其他函数使用的工厂中的常量。这只是我在主应用程序模块上设置的 angular.constant()。

我找到了一些其他帖子,但不确定如何继续,我需要将我的常量依赖项注入到我的测试中吗?

【问题讨论】:

    标签: angularjs jasmine


    【解决方案1】:

    我自己有点新,但我认为您需要使用下划线名称下划线技巧来注入您的工厂:

    var fct;
    beforeEach(inject(function (_helpersFactory_) {
        fct = _helpersFactory_;
    }));
    

    这个博客使用了 mocha,但我发现它很有用,而且 Karma 的东西应该是一样的:https://www.airpair.com/angularjs/posts/testing-angular-with-karma

    是的,您还需要注入常量(链接显示了如何注入),但您发布的代码似乎没有使用常量,因此您在此特定测试中不需要它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 2017-10-07
      • 2016-10-22
      • 2013-09-29
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      相关资源
      最近更新 更多