Automated Test Script for Angular 4

In this article, we’ll take a look writing test for Angular 4 applications also known as Automated Test Script for Angular 4, which helps in developing applications in TDD(Test Driven Development) environment.

In Angular4, we have to write Test script with .spec.ts extension and we have number tools like Karma, Jasmine & Protractor.

Step 1.

Below screen-shot is the structure for my Angular4 application, in which I have one user-manager Module. You can see file name user-manager.spec.ts which is our Automated Test Script.

Step 2.

Writing Automated Test Script for our user-manager.service.ts below screen-shot you can see my UserManagerService class which has one method i.e is post-call which will create a user for me

Step 3.

Creating an Automated Test Script for our user-manager.service.ts, we have file name user-manager.spec.ts where will code our Automated Test Script add below code, here we will use MockBackend and MockConnection to execute the code in isolation. As in Unit Testing, our code is not dependent on all HTTP calls and database. We can group our tests with a methoddescribe(). Within this method, we can create test cases with the functionit().

Step 4.

Now writing down the test cases for our create() method of user-manager.service.ts, you need to just modify your ser-manager.spec.ts by below code which includes our first test case. Which contains mock backend connection which will give us response status 201 when it matches your expected data, which is written in JSON format in variable data.

Step 5.

Execute your Automated Test Script using npm test or ng test in your command line to see the result.

Step 6.

Success will open your karma in the browser shows all the result.

What did we do?

  • created service and write tests.
  • dependency injection in tests
  • mock dependencies with Jasmine
  • mock HTTP backend

This is how Automated Test Script for Angular4 is created and tested.