Зміст курсу
Introduction to QA Automation Testing
Introduction to QA Automation Testing
Introduction to Unit Testing
Unit Test is a type of test case designed to verify the functionality of a specific unit within the code. A unit typically refers to the smallest testable part of an application, such as a function, method, class, or module. The goal of a unit test is to ensure that this component behaves as expected in isolation from the rest of the program.
In this chapter, we will learn how to write some very basic unit tests for our application. Though a formal introduction to Unit Testing will be done in the next section - this chapter aims to explain the essence of Unit Testing through JavaScript using our own custom testing function rather than utilizing a testing framework.
It is important to note that in Unit Testing, we aim to test the Unit for as many cases or inputs as possible.It is important to include all the possible edge cases when writing unit tests. Knowing the code of a unit makes it easier to find potential edge cases.
Edge Case: An edge case refers to scenarios or inputs that lie at the extreme ends of the input space. These conditions or inputs are not necessarily unusual but are at the boundaries of what the function is expected to handle.
Input Space: The input space refers to the complete set of all possible inputs that a function can accept.
To understand edge case scenarios let's consider a function called calculateAverage
:
function calculateAverage(numbers) { if (numbers.length === 0) { return null; } let sum = 0; for (let i = 0; i < numbers.length; i++) { sum += numbers[i]; } return sum / numbers.length; } console.log(calculateAverage([])); // Output: null console.log(calculateAverage([42])); // Output: 42 console.log(calculateAverage([1e10, 2e10, 3e10])); // Output: 20000000000 console.log(calculateAverage([-1, -2, -3, -4, -5])); // Output: -3
Following are examples of some edge cases that explore some unique situations for the above function:
Passing an Empty Array
- Input:
[]
; - Expected Output:
null
;
Passing a Single Element Array
- Input:
[42]
; - Expected Output:
42
;
Passing an Array containing Large Numbers
- Input:
[1e10, 2e10, 3e10]
; - Expected Output:
2e10
;
Passing an Array containing Negative Numbers
- Input:
[-1, -2, -3, -4, -5]
; - Expected Output:
-3
;
Passing an empty or a single element array is an unlikely usage of the calculateAverage
function, however, it is still a possible input, therefore it is useful to test the function for these scenarios - same is true for the other edge cases. Testing for all possible edge cases ensures the robustness of the unit being tested.
Дякуємо за ваш відгук!