茉莉花测试没有看到嵌套功能

时间:2014-03-07 17:35:56

标签: javascript closures jasmine nested-function

我正在尝试为我编写的函数编写一个jasmine测试,该函数按其日期属性“过滤”三个最新的对象。我一直收到错误:
    TypeError:无法调用未定义的方法'filterTopPricepoints'

我的javascript:

function viewSingleProduct(){
prod_id = document.URL.substring(document.URL.lastIndexOf('?')+4);
viewProductFields();
viewTopThreePricepoints();

function viewProductFields() {
    // AJAX CALL APPENDING DATA TO SCREEN
};

function viewTopThreePricepoints(){

    getAllPricepoints();
    function getAllPricepoints(){
        // AJAX CALL TO APPEND PRICEPOINTS TO SCREEN
    }

    function filterTopPricepoints(allPricepointsArray, limit){
        var result = [];
        function compareDates(a,b) {
            if (a.date < b.date){
                return -1;
            }
            if (a.date > b.date){
                return 1;
            }
                return 0;
        }
        allPricepointsArray.sort(compareDates);
        allPricepointsArray.reverse();
        console.log(allPricepointsArray);
        for (var i = 0; i < limit; i++){
            result.push(allPricepointsArray[i]);
        }
        return result;
    }
}
}

我的茉莉花测试:

describe("View Single Product Tests", function() {

  it("Filters three pricepoints by date", function() {

  var pp1 = {date: "2014-02-25"};
  var pp2 = {date: "2014-02-26"};
  var pp3 = {date: "2014-02-27"};
  var ppArray = []
  ppArray.push(pp1);
  ppArray.push(pp2);
  ppArray.push(pp3);
  var filteredArray = viewSingleProduct.viewTopThreePricepoints.filterTopPricepoints(ppArray, 3);
  expect(filteredArray).toBe([{date: "2014-02-27"}, {date: "2014-02-26"}, {date: "2014-02-25"}]);
  }); 
});

我无法判断我是否在访问Jasmine方面的函数时出错,或者我在使用闭包时在JS方面犯了错误。正确方向的任何一点都会有所帮助。

1 个答案:

答案 0 :(得分:2)

您的函数filterTopPricepoints()viewTopThreePricepoints()内是“私有的”(就像本地变量一样)。因此无法从茉莉花测试中访问它。

一种可能的解决方案是将该功能移出其他功能:

function viewSingleProduct(){
    ...
    function viewTopThreePricepoints(){
      ...
    }
}

function filterTopPricepoints(allPricepointsArray, limit){
     ...
}