ANGULARJS Test two Jasmine Test Routing Controller Filter Event Service

Source: Internet
Author: User
Tags emit

Test your application

1. Test the route we need to detect if the route is working, whether it is found, or 404. We want to confirm that the routed event is triggered and that the expected template is actually loaded. Since routing changes the address (URL) and page content of a page, we need to detect if the route is loaded, whether the page is found, and what happens in the middle. A simple route code: Angular.module (' myApp ', [' Ngroute '])
. config (function ($routeProvider) {
$routeProvider
. When ('/', {
Templateurl: ' views/main.html ',
Controller: ' HomeController '})
. When ('/login ', {
Templateurl: ' views/login.html ',
Controller: ' Logincontroller '})
. Otherwise ({Redirectto '/'});
}) to test the route we need to do the following: (1) inject $route, $location and $rootscope services.
(2) Create a mock backend to process the XHR and get the template code.
(3) Set an address to run a $digest life cycle STEP1: Reference the service in the test and set up a mock back end to get the template from Templateurl. You can use $httpbackend to create assertions to determine that the specified template is loaded. Describe (' Routes test ', function () {
Simulating the module in the test
Beforeeach (module (' myApp '));
var location, route, Rootscope;
Beforeeach (Inject (
function (_$location_, _$route_, _$rootscope_) {
location = _$location_;
route = _$route_;
Rootscope = _$rootscope_;
}));
Describe (' Index route ', function () {
Beforeeach (Inject (
function ($httpBackend) {
$httpBackend. Expectget (' views/home.html ')
. Respond (+, ' main HTML ');
}));
Our test code is here.
});
}); STEP2: In order to test the routing with unit tests, we need to simulate the operation of the route in production. Routing is run with the digest life cycle, and when location is set, it uses a digest cycle to process the route, change the content of the page, and then end the route. With that in view, we need to explain the path changes in the test. In the test, we intend to test two states on the app's index route: when the user navigates to the first page, the specified controller shows them the first page, and when the user navigates to an unknown route, they are taken to the home page as defined in the otherwise function. We can test these conditions by establishing the $location service to pass paths. In order to trigger the location request, we are going to run a digest cycle (on $rootscope) and then detect that the controller is expected (in this case, "HomeController"). It (' Should load the index page on successful load of/',
function () {
Location.path ('/');
Rootscope. $digest (); Call Digest Loop
Expect (Route.current.controller)
. ToBe (' HomeController ')
});
It (' should redirect to the "Index path on Non-existent
Route ', function () {
Location.path ('/definitely/not/a/_route ');
Rootscope. $digest ();
Expect (Route.current.controller)
. ToBe (' HomeController ')}); 2. Test controller in the process of building unit tests, it is necessary to ensure that:
Set up the test to simulate the module;
A known scope instance is used to store an instance of the controller;
Scope-based testing of our expectations. To initialize a controller instance, you need to use the $new () method to create a new instance of a scope from $rootscope. This new instance establishes the scope inheritance that angular uses at run time. With this scope, it is possible to initialize a new controller and pass the scope as the $scope of the controller. Describe (' Unit controllers: ', function () {
Analog MyApp Module
Beforeeach (module (' myApp '));
Describe (' Framecontroller ', function () {
Local variables
var framecontroller, scope;
Beforeeach (Inject (
function ($controller, $rootScope) {
Create a child scope
Scope = $rootScope. $new ();
Create a new instance of Framecontroller
Framecontroller = $controller (' Framecontroller ',
{$scope: scope});
}));
Our test code is here.
});}); In Framecontroller, we have a clock that shows the current time at the top of the app. We can also access a user and his time zone. The code for the specific controller is as follows Angular.module (' Myapp.controllers ', [])
. Controller (' Framecontroller ',
function ($scope, $timeout) {
$scope. Time = {
Today:new Date ()
};
$scope. user = {
TimeZone: ' Us/pacific '
}
var updateclock = function () {
$scope. Time.today = new Date ();
};
var tick = function () {
$timeout (function () {
$scope. $apply (Updateclock);
Tick ();
}, 1000);
}
Tick ();}); We want to test two functions of the controller: the time has been defined, the user has been defined, and sometimes the area. It (' Should has today set ', function () {
Expect (Scope.time.today). tobedefined ();
});
It (' should has a user set ', function () {
Expect (Scope.user). tobedefined ();}); Another easy-to-understand example://Create a Scope object, true to indicate that it does not inherit the parent variable, so as not to bother the Var scope= $rootScope. $new (TRUE);//Find Somecontroller and Initialize scope  $controller (' $SomeController ', {$scope: scope}); You can also inject other mock service or resolve objects here//expect a Name property on the scope that has a value of some one$expect (scope.name). Toequal (' some one ');// It is expected that a greeting function should appear on the scope and the value after calling it is Hello,some One$expect (scope.greeting ()). Toequal (' Hello,some One '); 3. Test factories and service services can be functions, either classes or variables, so there is no fixed form of testing, but the steps and principles are similar. Inject the service, save it as a variable, call it if it is a function, if it is a class, new it, then check the member, and if it is a variable, compare its value.   var myclass;//injected Beforeeach (Inject (function (_myclass_) {myclass=_myclass_;     Assigned to an external variable for use in subsequent tests)); it (' SomeMethod should be 2 ', function () {var obj=new MyClass (); Expect (Obj.somemethod ()). Toequal (2);}); 4. Test filter first, to access the filter, simply inject the $filter service into our tests. So we get a way to find filters in this process:
Describe (' unit:filter tests ', function () {
var filter;
Simulate our references in the test
Beforeeach (module (' myApp '));
Beforeeach (Inject (function ($filter) {
Filter = $filter;
}));
});
With access to the controller, it is easy to set expectations on the output of the filter.
It (' should give us and decimal points ',
function () {
Expect (filter (' number ') (123, 2)). Toequal (' 123.00 ');
}); 5. When you test the template test template, we focus on ensuring that a specific content template is loaded and that the specific data in the template is displayed in the view. You can create an assertion that the template is loaded properly. To do this, you need to build a test to expect a request to the Home page template, and perform a change of view to verify that it is actually loaded. Describe (' unit:templates ', function () {
var $httpBackend,
Location
Route
Rootscope;
Beforeeach (module (' myApp '));
Beforeeach (Inject (
function (_$rootscope_, _$route_, _$httpbackend_, _$location_) {
location = _$location_;
Rootscope = _$rootscope_;
route = _$route_;
$httpBackend = _$httpbackend_;
}));
Aftereach (function () {
$httpBackend. Verifynooutstandingexpectation ();
$httpBackend. Verifynooutstandingrequest ();
});
Our test code is here.
});
You can now build tests to reflect expectations when navigating to different parts of your app.
It (' Loads the home template at/', function () {
$httpBackend. Expectget (' templates/home.html ')
. respond (200);
Location.path ('/');
Rootscope. $digest (); Call Digest Loop
$httpBackend. Flush ();
});
It (' Loads the dashboard template At/dashboard ', function () {
$httpBackend. Expectget (' templates/dashboard.html ')
. respond (200);
Location.path ('/dashboard ');
Rootscope. $digest (); Call Digest Loop
$httpBackend. Flush ();
}); Note that we did not return a template in the test (IS. Respond (200) instead of. Respond ("\<div\>\</div\>")). Since we are just verifying that the template is loaded in the request, there is no need to worry about what is shown. 6. Test events when we unit test the triggering of events, we are interested in what they actually call and whether the correct event is actually invoked. Second, we are primarily concerned with the data that handlers have in their need.
Using Jasmine's Helper Method Spnon () makes it very easy to establish an event test. Imagine that we are testing a controller that triggers a $emit function. Based on this function, we can build an expectation that the event is triggered and called with any arguments that we are interested in. Describe (' myApp ', function () {
var scope;
Beforeeach (Angular.mock.module (' myApp '));
Beforeeach (Angular.mock.inject (function ($rootScope) {
Scope = $rootScope. $new ();
});
});
Once the test has been built, it is easy to set a Spyon () call to the $emit or $broadcase event on the scope.

// ...
});
It (' should has emit called ', function () {
Spyon (Scope, "$emit");
Scope.closepanel (); Example
Or any event that could cause emit to be called
Expect (scope. $emit)
. Tohavebeencalledwith ("panel:closed",
Panel.id);
});
We can also test the event: set a $on () listener that is called after an event is triggered. To execute the $broadcast method,
You can simply call $broadcast on the scope and establish an expectation of the scope changes that the event will cause.
// ...
It (' should set the panel to closed state ',
function () {
Scope. $broadcast ("panel:closed", 1);
Expect (scope.panel.state). Toequal ("closed");
});

ANGULARJS Test two Jasmine Test Routing Controller Filter Event Service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.