Use Jasmine and Karma to test AngularJS page programs. jasmineangularjs
AngularJS is the best thing on JavaScript after jQuery. This is also the method that JavaScript development has always wanted. One of the main advantages of Angular is its Dependency Injection, which is very conducive to unit testing of code. But it's a little weird that I couldn't find a tutorial on how to perform unit tests anyway.
Of course there are a lot of good recommendations: Use the Jasmine testing framework and the Test Runner, but there is no complete tutorial on how to Test from scratch. So I wrote this article. I have found a lot of resources on the Internet to know how to do this, and you don't need to do this now (if you can see this article from the beginning ).
Please tell me any errors you see until I can say this is the best practice for testing Angular applications based on Karma and Jasmine.
Introduction
This article will guide you through installing all the tools required for automated testing using Karma and Jasmine. I don't care whether you actually use TDD (test-driven development) or TAD (test-assisted development). In this article, I assume you already have a file to test.
Install Karma
If you have not installed Node. js, download and install it on your own. After installation, open the terminal or command line and enter the following command:
npm install -g karma
File structure
The file structure is unrelated to our issue, but in the next test, the file structure I used is as follows:
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 test examples.
Configure 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 some questions, including the testing framework you want to use, whether you need an automatic monitoring file, and what testing and tested files are included. In our tutorial, we retain 'Jasmine 'as our default framework, enable automatic file monitoring, and include the following files:
../*.js../**.*.jsangular-mocks.js**/*.tests.js
These are relative paths, including 1) All under the parent directory. js file, 2) All Sub-directories under the parent directory. js file, 3) angular-mock.js under the current directory, 4) and the current directory (including subdirectories) All. tests. js files (I like to differentiate test files from other files in this way ).
Whatever file you choose, make sure you have introduced angular. js, angular-mock.js, and other files you need to use.
Start Karma
Now Karma can be started. Enter the following in the terminal:
karma start karma.config.js
This command will start the browser you listed in the configuration file on your computer. These browsers are connected to Karma instances in the form of sockets. You will see a group of active browsers and be told whether they are performing the test. I hope Karma has told you a summary of the final test results on each browser (for example, 15 of 16 passes and 1 fails ), unfortunately, you can only view the information in the terminal window.
A prominent feature of Karma is that you can use any device in the network to connect and test your code. Try to direct your mobile browser to the Karma service. You can find the URL of this test on any running browser on your computer. It should be similar to: http: // localhost: 9876 /? Id = 5359192. You can direct your mobile phone, virtual machine, or any other device's browser to [your IP address on the network]: 9876 /? Id = 5359192. Because Karma is running a Node. js instance, your testing machine will send the test to any browser pointing to it like a web server.
Basic Testing
Suppose you already have a file to be tested. The home. js file we want to 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();});
You can create a test case in the home. test. js file. Starting from 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 brand new (clean) controler and scope object at the beginning of each test case.
Home. tests. js
'Use strict '; describe ('mainctrl', function () {var scope; // We will use this scope in the test. // simulate our Application module and inject our own dependency beforeEach (angular. mock. module ('application'); // simulates the Controller and includes $ rootScope and $ controller beforeEach (angular. mock. inject (function ($ rootScope, $ controller) {// create an empty scope = $ rootScope. $ new (); // declare the Controller and inject the created empty scope $ controller ('mainctrl ', {$ scope: scope });}); // test starts from here });
From the code, you can see that we have injected our own scope, so we can verify its information externally. At the same time, do not forget to simulate the module itself (7th lines of code )! Now we are ready for the test:
Home. tests. js
// Test it from here ('could have variable text = "Hello World! "', Function () {detail CT (scope. text). toBe ('Hello World !);});
If you run this test, it can be executed in any browser pointing to Karma and the test passes.
Send $ resource request
Now we are ready to test the $ resource request. To complete this request, we need to use $ httpBackend, which is a simulated version of Angular $ http. We will create another variable named $ httpBackend. In the second beforEach block, inject _ $ httpBackend _ and point the newly created variable to _ $ httpBackend _. Next, we will 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'); });
Put together
Home. tests. js
'use strict'; describe('MainCtrl', function(){ var scope, $httpBackend;//we'll use these in our tests //mock Application to allow us to inject our own dependencies beforeEach(angular.mock.module('Application')); //mock the controller for the same reason and include $rootScope and $controller beforeEach(angular.mock.inject(function($rootScope, $controller, _$httpBackend_){ $httpBackend = _$httpBackend_; $httpBackend.when('GET', 'Users/users.json').respond([{id: 1, name: 'Bob'}, {id:2, name: 'Jane'}]); //create an empty scope scope = $rootScope.$new(); //declare the controller and inject our empty scope $controller('MainCtrl', {$scope: scope}); }); // tests start here it('should have variable text = "Hello World!"', function(){ expect(scope.text).toBe('Hello World!'); }); it('should fetch list of users', function(){ $httpBackend.flush(); expect(scope.users.length).toBe(2); expect(scope.users[0].name).toBe('Bob'); });});
Tips
Karma runs all test cases in all files. If you only want to run a subset of all tests, modify describe or it to ddescribe or iit to run some tests. If you do not want to run some tests, modify describe or it to xdescribe or xit to ignore the code.
You can also run your test on the html file page. The example code is as follows:
Home.runner.html
<!DOCTYPE html>
Articles you may be interested in:
- Unit Test Method in JavaScript AngularJS Library
- Test the compatibility of IE browser with JavaScript AngularJS
- E2e test instance in angularjs
- Unit Test instance in angularjs