Angularjs is the best thing that happens to JavaScript after jquery. This is the way JavaScript has always been developed. One of the main advantages of angular is its dependency injection (Dependency injection), which facilitates unit testing of code. But a little weird is that I couldn't find a tutorial on how to do unit tests anyway.
Of course there are many good recommendations: Use the Jasmine test framework and the Karma Test executor (test Runner), but there is not a complete tutorial on how to test from scratch. So I wrote this article. I've found a lot of resources on the Internet to know how to do it, and you don't need to do that now (if you've seen this article from the beginning).
Please tell me any errors you see until I can say this is a best practice based on Karma and jasmine test angular applications.
Introduced
This article will guide you through the installation of all the tools you need to use Karma and jasmine for automated testing. I don't care if you really 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 do not have Node.js installed, please download and install it yourself. After installation, open the terminal or command line to enter the command:
File structure
The file structure is not related to our topic, but in the next test, I used the following file structure:
Application
| angular.js |
angular-resource.js
| Home
| home.js
| Tests
| Home
| home.tests.js
| karma.config.js ('ll is created in the next step)
| angular-mocks.js
* I don't advocate this kind of document structure, I show it just for testing examples.
Configure Karma
Switch to the directory where you want to place the configuration file, and then enter the following command in the terminal to create the profile:
Karma Init karma.config.js
You will be asked questions, including the test framework you want to use, whether you need to automatically monitor the files, which tests to include, and what files are being tested. In our tutorial, we reserve ' Jasmine ' as our default frame, open file automatic monitoring, and include the following files:
.. /*.js
.. /**.*.js
angular-mocks.js
**/*.tests.js
These are relative paths that contain 1 of all. js files under the parent directory, 2 All. js files under all subdirectories of the parent directory, 3 angular-mock.js,4 under the current directory, and all. tests.js files under the current directory (including subdirectories) (I like to differentiate between test files and other files in this way).
No matter what file you choose, make sure you introduce Angular.js,angular-mock.js and other files you need to use.
Start Karma
You can now start the Karma and still enter it in the terminal:
Karma Start Karma.config.js
This command will start your browser on your computer that is listed in your configuration file. These browsers will connect to the Karma instance as sockets, and you will see a group of active browsers and be told whether they are performing a test. I wish Karma had told you the summary of the final test results on each browser (for example 16 of the 15 passed, 1 failed), unfortunately you can only see this information through the terminal window.
A prominent feature of karma is that you can use any device in your network to connect and test your code. Try to point your mobile browser to the Karma service, and you can find the URL of the test on any browser running on your computer. It should be similar to: http://localhost:9876/?id=5359192. You can point your mobile phone, virtual machine, or any other device's browser to [your IP address]:9876/?id=5359192 on the network]. Because Karma is running a node.js instance, your test machine, like a Web server, sends the test to any browser that points to it.
The basic test
Let's say you already have a file to test. 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 ();
});
We can create our test cases in the Home.test.js file. 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 as well as the $scope variables. We will do this in the Jasmine Beforeeach method, so that we can have a new (clean) controler and scope object at the start of each test case.
Home.tests.js
' Use strict ';
Describe (' Mainctrl ', function () {
var scope;
We will use this scope
//Simulate our application module in the test and inject our own dependency
Beforeeach (angular.mock.module (' Application '));
Simulates controller and contains $rootScope and $controller
Beforeeach (function ($rootScope, $controller) {
//Create an empty scope
scope = $rootScope. $new ();
Declares controller and injects the created empty scope
$controller (' Mainctrl ', {$scope: scope});
The test starts here
});
You can see from the code that we have injected our own scope, so we can verify its information outside of it. Also, don't forget to simulate the module itself (line 7th code)! We are now ready for the test:
Home.tests.js
The test starts here
with it (' should have variable text = ' Hello world! ', function () {
expect (scope.text). Tobe (' Hello world! ');
});
If you run this test, it can be executed in any browser that points to karma, and the test passes.
Send $resource Request
Now we are ready to test $resource request. To complete this request, we need to use the $httpBackend, which is an analog version of the angular $http. We'll create another variable called $httpBackend, in the second Beforeach block, inject the _$httpbackend_ and point the newly created variable to _$httpbackend_. Next we'll tell $httpBackend how to respond to requests.
$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 it all together.
Home.tests.js
' Use strict '; Describe (' Mainctrl ', function () {var scope, $httpBackend;//we ' ll use this in we 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 ');
});
});
Skills
Karma will run all the test cases in all files, if you only want to run a subset of all the tests, modify describe or it to run individual tests for Ddescribe or IIT. If you don't want to run them with some tests, modify describe or it for xdescribe or xit to ignore the code.
You can also run your tests on the HTML file page. The code for the example is as follows:
Home.runner.html