Kaigai Blog living abroad in my twenties

【My Study Note】What is testing?

JavaScript Programming

What is testing?

Commenting

When you write the code, adding a comment is a great way to help your team understand and remember the expected behavior that you had for the function. 

But there’s a downside to the comments. It allows you to write anything you like, so there are no limits to ambiguity. Also, the comment doesn’t need to follow any set structure. Which causes it difficult to understand what you wrote in a comment.

Testing Frameworks

There are many custom testing frameworks available in JavaScript. One of the strengths of such frameworks is that you don’t have to use comments to describe your expectations.

The test syntax itself becomes expectation documenting. When you write tests, those tests are a better alternative to comments in your source code because they specify what expectations your source code is trying to satisfy. Tests are also callable, meaning you can execute tests to check if expectations are met.

e.g. When you use JEST (One of the testing frameworks)

function concatStrings(first, second) {
    return first + second;
}
expect(concatStrings("abc", "def")).toBe("abcdef");

I’m essentially stating that I expect the calling concatStrings with abc and def, will return the value abcdef. Testing in JavaScript lets me verify that the function is behaving in the way I intended.

Red and Green

When tests fail, you say that they are red, and when they pass, you say that they are green. If a test fails, then it’s a sign that you need to write the code in such a way that it passes its test. Once your test passes, you need to improve both the app’s code and the test code, but without changing the behavior of either. This is known as refactoring.

Refactoring is the process in which you write your feature code so that it runs more efficiently or that it’s easier to read and thus easier to understand for other programmers on the team. This is done without affecting the results that the code produces.

Red-green-refactor cycle

It’s most likely that some of your tests will be red and some of them will be green. Red tests are a guide as to how you need to improve your code to cater to unmet expectations. 

As you continue to refine your code in response to red tests, it becomes a cyclical activity. This is often described as the red-green-refactor cycle. Additionally, this cycle is the basis of the TDD (Test-Driven Development) approach to programming.

TDD approach

  1. Write a failing test
  2. Write your source code so that the previously failing test now passes
  3. Optimize your source code without changing its results