Andrii Kucherenko
https://t.me/mathrandomcommunity
https://mathrandom.com
YouTube: @mathrandomjavascriptcommunity
https://codeberry.club/
// calculator.spec.ts
test('should summarize two numbers',
(t: ExecutionContext) => {
}
);
// calculator.spec.ts
test('should summarize two numbers',
(t: ExecutionContext) => {
t.is(sum(1, 2), 3);
}
);
➜ ava-ts git:(master) ✗ npm test
> ava-ts@1.0.0 test /Users/andrii_kucherenko/Workspace/lab/tdd-training/ava-ts
> ava
1 uncaught exception
Uncaught exception in __tests__/caclulator.spec.ts
__tests__/caclulator.spec.ts(4,8): error TS2304: Cannot find name 'sum'.
npm ERR! Test failed. See above for more details.
➜ ava-ts git:(master) ✗ npm test
> ava-ts@1.0.0 test /Users/andrii_kucherenko/Workspace/lab/tdd-training/ava-ts
> ava
1 uncaught exception
Uncaught exception in __tests__/caclulator.spec.ts
__tests__/caclulator.spec.ts(5,20): error TS2345: Argument of type '3' is not assignable to parameter of type 'void'.
➜ ava-ts git:(master) ✗ npm test
> ava-ts@1.0.0 test /Users/andrii_kucherenko/Workspace/lab/tdd-training/ava-ts
> ava
1 test failed
should summarize two numbers
/Users/andrii_kucherenko/Workspace/lab/tdd-training/ava-ts/__tests__/caclulator.spec.ts:5
4: test('should summarize two numbers', (t: ExecutionContext) => {
5: t.is(sum(1, 2,), 3);
6: });
Difference:
- 0
+ 3
npm ERR! Test failed. See above for more details.
Bridge from task to implementation
Improved code
Tests as documentation
Safe refactoring
Increases assurance of correctness
String Calculator
This classic kata guides you step by step through the implementation of a calculator that receives a String
as input.
It is a good exercise on refactoring and incremental implementation. It is also a good candidate for practising TDD.
First step
Create a function add
that takes a String
and returns a Number.
""
, "1"
, "1.1,2.2"
.
Many numbers
Allow the add
method to handle an unknow number of arguments.
Newline as separator
Allow the add
method to handle newlines as separators:
"1\n2,3"
should return "6"
."175.2,\n35"
is invalid and should return the message "Number expected but '\n' found at position 6."
Missing number in last position
Don’t allow the input to end in a separator.
"1,3,"
is invalid and should return the message Number expected but EOF found.