Jasmine:尝试测试 AngularJS 工厂函数

Jasmine: Trying to test an AngularJS factory function

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

这是我工厂的片段:

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() 。

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

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

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

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

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