Test driven development TDD

 Test Driven Development (TDD) in action:

If we are building a simple calculator application that can add and subtract two numbers. We'll start by writing a failing test that specifies the behavior we want to implement:

---------

test("Addition of two numbers", () => {

  const sum = add(2, 3);

  expect(sum).toBe(5);

});


test("Subtraction of two numbers", () => {

  const difference = subtract(5, 2);

  expect(difference).toBe(3);

});

--------(

In this example, we have two test cases. The first test case expects the add function to return the sum of two numbers (2 and 3) as 5. The second test case expects the subtract function to return the difference of two numbers (5 and 2) as 3.

Now, let's write the implementation of add and subtract functions:
-----

function add(a, b) {

  return a + b;

}


function subtract(a, b) {

  return a - b;

}

-------
Now that we've written our implementation, we can run our tests again to see if they pass:

PASS Addition of two numbers
PASS Subtraction of two numbers

Since both tests pass, we know that our implementation is correct. However, TDD doesn't stop here. We want to make sure our code is as robust and maintainable as possible, so let's add some edge cases to our test suite:
-------
test("Addition of two negative numbers", () => {
  const sum = add(-2, -3);
  expect(sum).toBe(-5);
});

test("Subtraction of a negative number from a positive number", () => {
  const difference = subtract(2, -3);
  expect(difference).toBe(5);
});

test("Subtraction of a positive number from a negative number", () => {
  const difference = subtract(-2, 3);
  expect(difference).toBe(-5);
});

------
In these new tests, we're testing edge cases that weren't covered in our original tests. We're making sure that our functions can handle negative numbers and that the order of the arguments doesn't affect the result of the subtraction operation.

Now, we can run our tests again and see if they pass:
----
PASS Addition of two numbers
PASS Subtraction of two numbers
PASS Addition of two negative numbers
PASS Subtraction of a negative number from a positive number
PASS Subtraction of a positive number from a negative number
------
All tests pass, so we know that our code is robust and working as intended. This is an example of TDD in action - we wrote failing tests first, then implemented our code to make the tests pass, and finally added edge cases to make sure our code is robust and maintainable.

------
Read about TDD

https://www.ibm.com/garage/method/practices/code/practice_test_driven_development/

https://www.guru99.com/test-driven-development.html


https://www.linkedin.com/pulse/test-driven-development-tdd-why-you-should-care-lance-harvie

Comments

Popular posts from this blog

100 stable and 100 unstable job roles for 2025–2030

Next big wave of well paying jobs may come from engineering sector in India. Plan for your kids

Secret to Sustainable Employment