0

我正在尝试为我编写的函数编写一个茉莉花测试,该函数通过日期属性“过滤”三个最近的对象。我不断收到错误:
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 端出错。朝着正确方向的任何一点都会有所帮助。

4

1 回答 1

2

您的函数filterTopPricepoints()在内部是“私有的” viewTopThreePricepoints()(如局部变量)。因此无法从 jasmine 测试中访问它。

一个可能的解决方案可能是将函数移出其他函数:

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

function filterTopPricepoints(allPricepointsArray, limit){
     ...
}
于 2014-03-07T17:44:58.793 回答