質問

I am trying to write a jasmine test for a function I wrote that "filters" out the three most recent objects by their date attribute. I keep getting the error:
TypeError: Cannot call method 'filterTopPricepoints' of undefined

My 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;
    }
}
}

And my Jasmine test:

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"}]);
  }); 
});

I can't tell if I am making an error in accessing the function on my Jasmine side, or if I am making a mistake on the JS side with my use of closures. Any point in the right direction would be helpful.

役に立ちましたか?

解決

Your function filterTopPricepoints() is "private" inside viewTopThreePricepoints() (like a local variable). Therefore it cannot be accessed from the jasmine test.

A possible solution could be to move the function out of the other function(s):

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

function filterTopPricepoints(allPricepointsArray, limit){
     ...
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top