Зміст курсу
Introduction to QA Automation Testing
Introduction to QA Automation Testing
Writing Unit Tests
The overall syntax of writing Unit Tests in Jest is explained in the following video:
An alternative version of test
is the it
function, having identical syntax, but offers slight convenience due to its shorter name.
The test
or it
function have the following syntax:
testDescription
is a short description of what the test is about.callback
is simply an inline function which contains the test code.timeout
is an optional argument, representing a value in milliseconds. If the respective test takes longer than this duration then it's considered a failure. This value is 5000 or 5 seconds by default.
It is important to note that multiple expect statements can be included into a single test case:
This gives us the ability to perform all kinds of tests thoroughly.
In case you have to perform testing in a different language, you can simply look at the documentation of the testing framework being used, which typically lists all the available methods for assertions.
The expect
function expects one argument and the expect function itself returns an object of a class called JestMatchers, which has some useful methods for performing assertions. One of those methods being toBe
, which we previously looked at. The following code breaks down the syntax:
The example above creates two extra variables, namely, returnValue
to store the result of sum(-1, -2)
, and matcherObject
to store the object returned by expect(returnValue)
.
The conventional syntax however, is shorter and more concise. We can simply call the sum function directly inside the expect
brackets, which returns the calculated result and in-turn passes it into the expect function, hence, eliminating the need to an extra returnValue
variable:
We can further shorten our code by simply eliminating the matcherObject
variable. The expect
function returns the matcher object itself, therefore the toBe
method can be executed directly from it accordingly:
The above mentioned syntax is the conventional method of writing simple assertions using Jest. The toBe
method is known as a Matcher, since it matches or compares two values. Matchers are provided by the Matcher Object returned by the expect
function.
To toBe
matcher compares two values of any primitive type strictly.
There are many Matchers for testing various types of values. The toBe
matcher is used for comparing primitive types like integers, floats, strings or characters. However, it is not usable for comparing more complicated items like arrays or objects since it doesn't perform a deep comparison.
Дякуємо за ваш відгук!