Recently more interested in front-end testing, especially the Nodejs + Karma + Jasmine test for angular. Look around, make a record, intermittent updates.
< a > Test Angular's Service1 with Jasmine. Throw the code First:
var app = Angular.module (' Application ', []);
App.factory (' MyService ', function () {var service = {}; Service.one = 1; Service.two = 2; return service;});
2. How to test this angular service?
Describe (' MyService test ', function () {Describe (' when I call Myservice.one ', function () {It (' returns 1 ', Functio N () {var $injector = angular.injector ([' Application ']); var myservice = $injector. Get (' MyService '); Expect (Myservice.one). toequal (1); }) })});
3. The results are as follows:
Because I ran a different test, so.
4. Another way to test the service
Use ' Invoke ' to pass the service to a function
Describe (' Myservice test2 ', function () { describe (' when i call Myservice.one ', function () { it (' returns 1 ', function () { var mytestfunction = function (Aservice) { expect ( aService.one ). Toequal (1); } Mytestfunction. $inject = [ ' MyService ' ]; var myinjector = angular.injector ([ ' Application ' ]); myinjector.invoke ( myTestFunction ); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp; }) });
5. Add an easier way:
Beforeeach is Jasmine's grammar, which runs before it ().
It is important to note that the inject function is not a ANGULARJS standard package, it is in the Ngmock module, and only work with Jasmine.
Describe (' MyService test3 ', function () {Describe (' when I call Myservice.one ', function () {Beforeeach (module (' App Lication ')); It (' returns 1 ', Inject (function (MyService) {///parameter name is the service name expect (Myservice.one). toequal (1); })) })});
Angular tests based on Karma and Jasmine (ongoing updates)