我想在javascript中编写一个特权方法的测试(jasmine和javascript都是新的),但不幸的是我很难理解如何正确地公开我的方法。
我知道我无法测试私有方法,但我认为我应该能够测试特权方法 - 是对还是错?
当我在浏览器中运行代码时,调用song.bottlesOrBottle();
会返回正确的形容词。然而,我测试bottleOrBottles();
是否暴露的茉莉花代码返回undefined。
显然,我还不了解JavaScript或茉莉(可能两者)中的概念。有人可以通过解释我的测试失败原因来帮助我吗?我将不胜感激。谢谢!
PS:我也尝试将bottlesOrBottle
解压缩到原型方法中,但是虽然代码在我的浏览器中正确运行,但我编写的茉莉花测试都没有通过原型。如果有必要,我可以在这里粘贴该代码,但是首先要集中精力理解一个概念。再次,谢谢你的帮助。
CODE
function Song(numberOfBottles){
var self = this;
var lyrics = [];
// bottlesOrBottle();
this.bottlesOrBottle = function (){
return adjectiveToUse();
}
function adjectiveToUse(){
return (self.numberOfBottles <=1? '' : 's');
}
setNumberOfBottles();
function setNumberOfBottles(){
var error = 'this constructor accepts numbers between 1 and 10';
if (numberOfBottles === undefined || numberOfBottles < 1 || numberOfBottles > 10) {
throw new Error(error);
} else{
self.numberOfBottles = numberOfBottles;
};
}
}
TEST
describe('Song Constructor', function() {
var song;
beforeEach(function(){
song = new Song(10);
});
describe('if not passed an argument', function(){
it('should throw an error', function(){
expect(function(){new Song()}).toThrow(new Error('this constructor accepts numbers between 1 and 10'));
});
});
describe('if passed a number less than 1 or greater than 10', function(){
it('should throw an error', function(){
expect(function(){new Song()}).toThrow(new Error('this constructor accepts numbers between 1 and 10'));
});
});
describe('if passed a number between 1 - 10', function(){
it('should store numberOfBottles property on creation of a new song', function(){
expect(song.numberOfBottles).toEqual(10);
});
});
describe('bottlesOrBottles method', function(){
it('is exposed', function(){
debugger;
expect(song.bottlesOrBottles()).toEqual('s');
});
});
});