Test the AngularJS page program using Jasmine and Karma

  • 2021-01-25 06:58:14
  • OfStack

AngularJS is the best thing to happen to JavaScript since jQuery. This is the way JavaScript has always wanted to develop 1. One of the main advantages of Angular is its dependency injection (Dependency Injection), which is great for unit testing code. It's a little weird that I haven't found a single tutorial on how to do unit testing in any way.

Of course, there are many good recommendations: using the Jasmine test framework and the Karma test executor (Test Runner); But there is no complete tutorial on how to test from scratch. So I wrote this article. I found a lot of resources online to figure out how to do this, and you don't need to do this right now (if 1 started reading this article).

Please tell me any errors you see until I can say that this is best practice for testing Angular applications based on Karma and Jasmine.

introduce

This article guides you through the installation of all the tools you need to automate your tests using Karma and Jasmine. I don't care if you're actually using TDD (Test Driven Development) or TAD (Test Assisted Development), for the purposes of this article, I'm assuming you already have one file to test.

Install Karma

If you do not have ES32en. ES33en installed, please download and install it yourself. After installation, open the terminal or command line and type 1:


npm install -g karma

File structure

The file structure is not relevant to our topic, but for the following tests, I used the following file structure:


Application
| angular.js
| angular-resource.js
| Home
 | home.js
| Tests
 | Home
 | home.tests.js
 | karma.config.js (will be created in the next step)
 | angular-mocks.js

* I do not advocate this document structure; I show it only for testing examples.

Configuration Karma

Switch to the directory where you want to place the configuration file and enter the following command in the terminal to create the configuration file:


karma init karma.config.js

You will be asked a few questions, including which testing framework you want to use, whether you need to automatically monitor files, which tests and tested files are included, etc. In our tutorial we left 'Jasmine' as our default framework to enable automatic file monitoring and include the following files:


../*.js
../**.*.js
angular-mocks.js
**/*.tests.js

These are relative paths, includes 1) all of the parent directory. js file, 2) the parent directory under the subdirectories in a directory of all. js file, 3) the current directory angular - mock. js, 4) as well as the current directory (contain subdirectories) at all. tests. js files (I like this way to differentiate between the test files and other files).

Whichever file you choose, make sure you include angular.js, angular-mock.js, and any other files you need to use.

Start the Karma

Now you are ready to start ES73en. Once again, type:


karma start karma.config.js

This command will launch the browser you listed in the configuration file on your computer. Each of these browsers will be connected to an instance of ES78en as ES77en, and you will see a group of active browsers and be told if they are running tests. I wish ES79en had given you a summary of the final test results on each browser (e.g. 15 passes and 1 failure out of 16), but unfortunately you can only see this information through a terminal window.

One of the great features of Karma is that you can use any device on the network to connect and test your code. Try pointing your mobile browser to the ES83en service. You can find the ES84en address for this test on any running browser on your computer. It should look something like: http://localhost:9876/? id = 5359192. You can point the browser of your mobile phone, virtual machine, or any other device to [your ES88en address on the network]:9876/? id=5359192. Because Karma is running an instance of Node.js, your test machine will act like an web server and will send tests to any browser that points to it.

Basic tests

Let's say you already have 1 file to test. The home.js file we will use is as follows:

home.js


'use strict';
 
var app = angular.module('Application', ['ngResource']);
 
app.factory('UserFactory', function($resource){
 return $resource('Users/users.json')
});
 
app.controller('MainCtrl', function($scope, UserFactory) {
 $scope.text = 'Hello World!';
 $scope.users = UserFactory.get();
});

We can create our test cases in the file ES106en.ES107en.ES108en. Let's start with the simple test: $scope.text should be equal to 'Hello World! '. To complete this test, we need to simulate our Application module and the $scope variable. We will do this in the beforeEach method of Jasmine so that we can have a new (clean) controler and scope object at the beginning of each test case.

home.tests.js


'use strict';
 
describe('MainCtrl', function(){
 var scope;
// We're going to use this in our tests scope
 
 
// To simulate our Application Modules and inject our own dependencies 
 beforeEach(angular.mock.module('Application'));
 
// simulation Controller , and contains  $rootScope  and  $controller
 beforeEach(angular.mock.inject(function($rootScope, $controller){
  
// create 1 empty  scope
  scope = $rootScope.$new();
  
// The statement  Controller And inject the created empty  scope
  $controller('MainCtrl', {$scope: scope});
 });
 
//  The test starts here 
});

From the code you can see that we have injected our own scope, so we can verify its information outside of it. Also, don't forget the emulation module itself (line 7)! We are now ready for the test:

home.tests.js


//  The test starts here 
it('should have variable text = "Hello World!"', function(){
 expect(scope.text).toBe('Hello World!);
});

If you run this test, it can be run in any browser pointing to Karma, and the test passes.

Send a request for $resource

We are now ready to test the $resource request. To complete this request, we need to use $httpBackend, which is a mock version of Angular $http. We will create another variable called $httpBackend, and in the second beforEach block, inject _$httpBackend_ and point the newly created variable to _$httpBackend_. Next we tell $httpBackend how to respond to the request.


$httpBackend = _$httpBackend_; 
$httpBackend.when('GET', 'Users/users.json').respond([{id: 1, name: 'Bob'}, {id:2, name: 'Jane'}]);

Our test: home.tests.js


it('should fetch list of users', function(){
   $httpBackend.flush();
   expect(scope.users.length).toBe(2);
   expect(scope.users[0].name).toBe('Bob');
  });

They all start at 1

home.tests.js


Application
| angular.js
| angular-resource.js
| Home
 | home.js
| Tests
 | Home
 | home.tests.js
 | karma.config.js (will be created in the next step)
 | angular-mocks.js
0

skills

Karma will run all test cases in all files. If you only want to run a subset of all tests, change describe or it to ddescribe or iit to run individual tests. If there are tests you don't want to run, change describe or it to xdescribe or xit to ignore the code.

You can also run your tests on the html page. The example code is as follows:
home.runner.html


Application
| angular.js
| angular-resource.js
| Home
 | home.js
| Tests
 | Home
 | home.tests.js
 | karma.config.js (will be created in the next step)
 | angular-mocks.js
1


Related articles: