2016-02-25 146 views
2

我有一個對象,並正在嘗試單元測試其方法與茉莉花之一。我得到的錯誤是undefined is not a function (evaluation foo.initArr())無法單元測試原型方法

foo.js

function Foo(value) { 
    if(typeof value !== "string") { 
    value = ""; 
    } 

    var foo = { 
    value: value 
    }; 

    return foo; 
}; 

Foo.prototype.initArr = function(arr) { 
    if(arr) { 
    // do nothing 
    } else { 
    // initialize array 
    arr = []; 
    } 

    return arr; 
}; 

foo.spec.js

describe("foo.js", function() { 
    var validVal, 
    numberVal, 
    nullVal, 
    falseVal, 
    trueVal, 
    undefinedVal; 

    beforeEach(function() { 
    validVal = "PrQiweu"; 
    numberVal = 420; 
    nullVal = null; 
    falseVal = false; 
    trueVal = true; 
    undefinedVal = undefined; 
    }); 

    afterEach(function() { 
    validVal = null; 
    numberVal = null; 
    falseVal = null; 
    trueVal = null; 
    undefinedVal = null; 
    }); 

    describe("Foo:constructor", function() { 
    it("should return an empty string if the passed value isn't a string", function() { 
     var foo = new Foo(numberVal); 
     expect(foo.value).toEqual(""); 
    }); 

    it("should return a string if the passed value is a string", function() { 
     var foo = new Foo(validVal); 
     expect(foo.value).toEqual(jasmine.any(String)); 
    }); 

    describe("method:arr", function() { 

     it("should return an empty array if it wasn't passed one", function() { 
     var foo = new Foo(validVal); 
     expect(foo.initArr()).toBe([]);   
     }); 
    }) 
    }); 
}); 

最後一次測試案例失敗。我不認爲間諜在這裏是必需要麼,但我可能是錯的。我意識到initArr功能是沒有意義的,所以請忽略我的白癡。

爲什麼最後的測試失敗的情況下,我怎麼能解決這個問題?

回答

3

您的構造函數返回一個不同的foo,它沒有原型函數。

function Foo(value) { 
    if(typeof value !== "string") { 
    value = ""; 
    } 

    var foo = { 
    value: value 
    }; 

    return foo; // This foo your locally defined foo var, 
}; 

也許你的意思是這樣寫:

function Foo(value) { 
    if(typeof value !== "string") { 
    value = ""; 
    } 
    this.value = value; 
};