1

I want to write TDD/BDD tests for this problem for my training. This problem's scenarios are:

For every basket above $50, 2% of total will calculate as discount

For every basket above $100, 5% of total will calculate as discount

So I wrote these tests(using Jasmine):

describe("discount", function () {    
    describe("When total price calculated", function () {
        it("Should get 4% discount if it is more than $100", function () {
            let total = 110;
            expect(checkout.calcDiscountBiggerThan100(total)).toBe(total / 0.04);
        });
        it("Sould get 2% discount if it is more than $50 and less than $100", function () {
            let total = 70;
            expect(checkout.calcDiscountBetween50And100(total)).toBe(total % 0.02);
        })
        it("Sould calc no discount if it less than $50", function () {
            let total = 45;
            expect(checkout.calcDiscountBetween50And100(total)).toBe(0);
        })
    });    
});

But when I want to write the code for them, I don't know how should I do! If I want to write like this:

class checkout{
    calcDiscount(total) {
        if (total > 100)
            return total * 0.04
        if (total > 50)
            return total * 0.02
        return 0;
    }
}

Then I have 2 problem here.

  1. I don't follow my scenarios
  2. How can I follow open/close principle here(What should my classes will be)

And if I want to act as my test I will have:

calcDiscountBiggerThan100(total) {
    if (total > 100)
        return total * 0.04
}
calcDiscountBetween50And100(total) {
    if (total > 50)
        return total * 0.02
}

And here again I have problem that how should I refactor it it for open/closed principle.

Please note that, it's possible to change $100 to $120. And may be another rules add to these rules. then should I have a class with the name of DiscountBetween50And100 or what?

I'm new in testing. please help me

Boolood
  • 79
  • 9

0 Answers0