【问题标题】:console.log in karma angularjs method testingconsole.log in karma angularjs 方法测试
【发布时间】:2016-03-07 15:05:58
【问题描述】:

我有点困惑,为什么我将undefined 作为我正在测试的函数的返回值。

这是我正在测试的功能:

 $scope.entityItemsIntoObjectChecked = function (entityItems) {
    newEntityWithChecked = entityItems.map(function (value) {
        return { "val": value, "checked": false }; 
    });
    shareDataService.setEntityArray(newEntityWithChecked);
}

以及我的测试套件的一部分:

it("should arrange an array into ovject with extra value for entities + depots", inject(function (shareDataService) {
        var dummyEntityArray = ["ent1", "ent2", "ent3"];
        var expectedObjectArray = [{ val: "ent1", checked: false }, { val: 'ent2', checked: false }, { val: 'ent3', checked: false }];

        expect(mainScope.entityItemsIntoObjectChecked).toBeDefined();
        mainScope.entityItemsIntoObjectChecked(dummyEntityArray);
        console.log(mainScope.entityItemsIntoObjectChecked(dummyEntityArray))
}))

我期待console.log(mainScope.entityItemsIntoObjectChecked(dummyEntityArray)) 行根据我之前在mainScope.entityItemsIntoObjectChecked(dummyEntityArray); 行上传入的数组dummyEntityArray 输出我的数组

但我在 console.log 上得到 undefined。这是为什么呢?

【问题讨论】:

    标签: javascript angularjs testing jasmine karma-jasmine


    【解决方案1】:

    您的$scope.entityItemsIntoObjectChecked 方法不返回任何内容,因此返回值将是undefined。

    您可以从该方法返回 newEntityWithChecked 数组,也可以监视您的 shareDataService.setEntityArray 方法以验证是否正在传递预期的数组。

    您可以在此处阅读有关间谍的文档:http://jasmine.github.io/2.0/introduction.html#section-Spies

    【讨论】:

    • 是否可以在 jasmine 中调用函数并为其分配 var?例如,我希望将mainScope.entityItemsIntoObjectChecked(dummyEntityArray); 分配给一个var,然后传递给我的下一步测试,即expect(mainScope.methodWhichChangesArrayToObject(mainScope.entityItemsIntoObjectChecked(dummyEntityArray)).toEqual( <<object within array>>)
    • 下一步是指另一个规范吗?通常不建议让一个规范依赖于另一个规范。您可以在要测试的规范中调用必要的方法methodWhichChangesArrayToObject
    • 好的,这为我解决了问题。非常感谢。理解这个测试很难,主要是因为如果你明白我的意思,这似乎很容易?我一直在想我错过了一些巨大的东西......
    猜你喜欢
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 2014-09-20
    相关资源
    最近更新 更多