我试图通过做一些katas来练习我的javascript测试。我不太明白为什么这不起作用,我设法用类似的销售功能很容易地做一个ruby版本。
ticketClark.js
var TicketClerk = function() {
this.till = { 25: 0, 50: 0, 100: 0 };
};
TicketClerk.prototype.sell = function(array) {
for (var i = 0; i < array.length; i++) {
if (this.canMakeChange(array[i])) {
this.giveChange(array[i]);
} else {
return "NO";
}
}
return "YES";
};
TicketClerk.prototype.canMakeChange = function(note) {
if (note === 50) {
return this.till[25] > 0;
}
if (note === 100) {
return this.canGiveFiftyTwentyFive() || this.canGiveThreeTwentyFives();
}
return true;
};
TicketClerk.prototype.giveChange = function(note) {
if (note === 25) {
this.till[25]++;
}
if (note === 50) {
this.till[25]--;
this.till[50]++;
}
if (note === 100 && this.canGiveFiftyTwentyFive()) {
this.till[25]--;
this.till[50]--;
this.till[100]++;
}
if (note === 100 && this.canGiveThreeTwentyFives()) {
this.till[25] -= 3;
this.till[100]++;
}
};
TicketClerk.prototype.canGiveThreeTwentyFives = function() {
return this.till[25] > 2;
};
TicketClerk.prototype.canGiveFiftyTwentyFive = function() {
return this.till[25] > 0 && this.till[50] > 0;
};
test.js
describe("#TicketClerk", function() {
beforeEach(function() {
ticketClerk = new TicketClerk();
});
describe("#initialize", function() {
it("shows a hash of the money in the till, which starts with zero of each denominator", function() {
expect(ticketClerk.till).toEqual({ 25: 0, 50: 0, 100: 0 });
});
});
describe("#sell", function() {
it("entering 25, 25, 50 should return 'YES' as it can give change", function() {
ticketClerk.sell([25, 25, 50, 50]);
expect(ticketClerk.sell).toEqual("YES");
});
it("entering 50, 25, 50 should return 'NO' as it cannot give change", function() {
ticketClerk.sell([50, 25, 50]);
expect(ticketClerk.sell).toEqual("NO");
});
});
});
我遗漏了其他测试,我认为不需要。卡塔是以25美元的价格接受电影票,并改变了一系列客户。它应该返回&#34;是&#34;如果你能给每个人改变,并且&#34; NO&#34;如果你不能。
答案 0 :(得分:1)
您将方法名称传递给expect
语句而不是调用结果。您可以像这样更改它:
describe("#TicketClerk", function() {
beforeEach(function() {
ticketClerk = new TicketClerk();
});
describe("#initialize", function() {
it("shows a hash of the money in the till, which starts with zero of each denominator", function() {
expect(ticketClerk.till).toEqual({ 25: 0, 50: 0, 100: 0 });
});
});
describe("#sell", function() {
it("entering 25, 25, 50 should return 'YES' as it can give change", function() {
const result = ticketClerk.sell([25, 25, 50, 50]); // pass result
expect(result).toEqual("YES");
});
it("entering 50, 25, 50 should return 'NO' as it cannot give change", function() {
const result = ticketClerk.sell([50, 25, 50]); // pass result
expect(result).toEqual("NO");
});
});
});