Unit Testing

Definition Practice of Writing code to test our code and run it in automated fashion.

Why do we need it? Generally to test our code we will run the code in the browser and go to the particular page and fill few values and test the functionality, which is bit time consuming. Instead we can write a code snippet to call our function and test the logic.  By this way, we can test most of the logic in the entire application quickly.

But most of the developers think that writing test code is time consuming because developers has to write the application code and then write the unit test code to test the application code. This results in maintenance cost as the developers has to write and maintain the test cases.But practically the maintenance cost of the application with automation is far less than without automation testing. One more advantage of automated testing is it helps us catch defects before releasing the software. It enforces us to write better and more reliable code

Important : Always be pragmatic while writing test.

Types of test:

Unit Test – Test a code in isolation without external resources. In Angular terms, testing a component in isolation without its template and services. We use a fake services or fake router to work.

Integration Test : Testing a component along with its template.

End-to-End test: Test the entire application as a whole. We simulate the real user. It gives more confidence but it is slow and very fragile.

So write more unit/Integration tesst and less end-end-end test.

Unit Test Fundamentals:

Test are first class citizens. Writing test follows clean coding practices:

  1. Single responsibility.
  2. Small Functions.
  3. Proper naming.

How to write a basic test:

First create a file with name as the <compoent_name>.spec.ts

Jasmine provides bunch of methods to write test.

The two functions we use most of the time :

  • describe() – to define suite which is group of related tests.
  • it() – to define a spec or test.

Setup and Tear Down

The general procedure taken while we testing the component are: Arrange , ActAssert.

Arrange: We arrange the component required for testing by creating the instance of it.

Act: We act on the particular method that needs to be tested and save the results.

Assert: At last assert the results which we got to check for the particular output.

While we do these procedure of testing the component the first part of initialization procedure is the repeated act. So we move this common code to single place to avoid duplication. Each test should run in the isolated world so that the execution of one test should not affect the execution of other tests. So in Jasmine we have method called beforeEach(), afterEach(), beforeAll(), afterAll().

So in testing terms, the code we write in beforeEach() is called as setup and the code we write in afterEach() is called tear down.