I'm trying to test a simple service but I'm getting an Unkown Provider error. Here is the service definition:
var sessionManager = angular.module('MyApp.SessionManager', ['ngResource']);
sessionManager.factory('UserService', function($resource) {
var UserService = $resource('/api/users/:key', {}, {
getNewUUID: {
method: 'GET',
params: {
action: 'getNewUserUUID'
}
}
});
return UserService;
});
and here is the test:
describe('Testing SessionManager', function() {
var userService;
beforeEach(function() {
module('MyApp.SessionManager');
inject(function($injector) {
userService = $injector.get('UserService');
});
});
it('should contain a UserService', function() {
expect(userService).toBeDefined();
});
});
I can't seem to see the problem, I know that the UserService javascript file is being called because I can get a console log at the top of the file, however if I put it in the service definition I don't see it get called. So for some reason it's like Angular is not instantiating my service?
I realized that the problem was my module MyApp.SessionManager was being replaced because I thought you could declare dependencies every time it was reopened to add a module. The code above is fine if of course the service is actually surviving up until the tests.
Related
I have few questions with to write a proper unit test for a service using jasmine as framework and karma as test runner.
here is what i implemented in example-service.js:
export default class ExampleService {
constructor($resource, $http, $urlMatcherFactory) {
'ngInject';
this.$resource = $resource;
this.$http = $http;
this.$urlMatcherFactory = $urlMatcherFactory;
}
exampleMethodOne() {
//some code lines
}
exampleMethodTwo() {
//some code lines
}
}
ExampleService.selector = 'myExampleService';
Here what i wrote in my test example-service.test.js
let myExampleService, $httpBackend, $urlMatcherFactory;
beforeEach(() => {
angular
.module('exampleApp', ['ngResource'])
.service(ExampleService.selector, ExampleService);
angular.mock.module('exampleApp');
});
beforeEach(inject((_myExampleService_, _$httpBackend_,
_$urlMatcherFactory_) => {
myExampleService = _myExampleService_;
$httpBackend = _$httpBackend_;
$urlMatcherFactory = _$urlMatcherFactory_;
}));
i have imported the angular-mocks.js, angular-resource.js and example-service.js
when i try this scenario the console will throw a Error: [$injector:unpr] Unknown provider: $urlMatcherFactoryProvider <- $urlMatcherFactory <- myExampleService error.
please help me to solve this.
I suppose $urlMatcherFactory refers to UI router service, and UI Router wasn't loaded.
It's not recommended to use real router in unit tests because it provides extra moving parts and breaks isolation between units. As a rule of thumb, every unit but a tested one should be mocked.
$urlMatcherFactory stub methods have to be configured to return expected values. Since they are used during ExampleService construction, they should be configured prior to service instantiation:
let removeAllUrlMock;
beforeEach(() => {
removeAllUrlMock = jasmine.createSpyObj('removeAllUrl', ['format']);
$urlMatcherFactory = jasmine.createSpyObj('urlMatcherFactory', ['compile']);
$urlMatcherFactory.compile.and.returnValue(removeAllUrlMock);
angular
.module('exampleApp', ['ngResource'])
.service(ExampleService.selector, ExampleService);
angular.mock.module('exampleApp');
angular.mock.module({ $urlMatcherFactory });
});
This can be tested with:
expect($urlMatcherFactory.compile).toHaveBeenCalledOnce();
expect($urlMatcherFactory.compile).toHaveBeenCalledWith('../api/v1/user/{Id}/remove/all');
expect(myExampleService.removeAllUrl).toBe(removeAllUrlMock);
Then specific removeAllUrl calls can be mocked and tested when used:
removeAllUrlMock.format.and.returnValue('../api/v1/user/foo/remove/all');
myExampleService.removeProduct('foo');
expect(removeAllUrlMock.format).toHaveBeenCalledOnce();
expect($urlMatcherFactory.compile).toHaveBeenCalledWith(
jasmine.objectContaining({ id: 'foo' })
);
Since $urlMatcherFactory is utility service that doesn't provide much moving parts and supposed to be predictable, it can alternatively be imported and used directly, without UI router module:
import { UrlMatcherFactory } from '#uirouter/angularjs';
...
beforeEach(() => {
angular
.module('exampleApp', ['ngResource'])
.service(ExampleService.selector, ExampleService);
angular.mock.module('exampleApp');
angular.mock.module(($provide) => {
$provide.service('$urlMatcherFactory', UrlMatcherFactory });
});
});
Then it's just has to be spied:
spyOn(myExampleService, 'removeAllUrl').and.callThrough();
myExampleService.removeProduct('foo');
expect(removeAllUrlMock.format).toHaveBeenCalledOnce();
expect($urlMatcherFactory.compile).toHaveBeenCalledWith(
jasmine.objectContaining({ id: 'foo' })
);
I'm trying to test a service documentViewer that depends on some other service authService
angular
.module('someModule')
.service('documentViewer', DocumentViewer);
/* #ngInject */
function DocumentViewer($q, authService) {
// ...
this.view = function(doc) {
//...
}
}
This is what my test looks like at the moment
it('test', inject(function($q) {
var doc = {
view: function() {
return $q.resolve(0);
}
};
var auth = {
refreshProfileData: function() {
return $q.resolve(0);
},
};
var viewer = createViewer(auth);
}));
function createViewer(auth) {
var viewer;
module({
authService: auth
});
inject(function(documentViewer) {
viewer = documentViewer;
});
return viewer;
}
The problem is I need to call inject to grab a $q, then use it to create my mocks, register my mocks with module, and then call inject again to grab the unit under test.
This results in
Error: Injector already created, can not register a module! in bower_components/angular-mocks/angular-mocks.js (line 2278)
I've seen lots of answers here on SO saying you can't call module after inject, but they don't offer any alternative to a scenario like the above.
What's the correct approach here?
PS: I'd like to avoid using beforeEach, I want each test to be self-contained.
module is used to define which modules will be loaded with inject and cannot be called after inject, this is chicken-egg situation.
The object accepted by module is used to define mocked services with $provide.value:
If an object literal is passed each key-value pair will be registered on the module via $provide.value, the key being the string name (or token) to associate with the value on the injector.
There can be no more than 1 function like createViewer that calls both module and inject. If this means that this kind of self-contained test is an antipattern, there is nothing that can be done about that. Angular testing works best with usual habits, including beforeEach and local variables.
In order to eliminate the dependency on $q, mocked service can be made a factory.
it('test', function () {
var authFactory = function ($q) {
return {
refreshProfileData: function() {
return $q.resolve(0);
},
};
};
// mocks defined first
module(function ($provide) {
$provide.factory('authService': authFactory);
});
var viewer;
inject(function(documentViewer) {
viewer = documentViewer;
});
// no module(...) is allowed after this point
var $q;
inject(function(_$q_) {
$q = _$q_;
});
var doc = {
view: function() {
return $q.resolve(0);
}
};
});
Question: how do I access a dynamically generated data in scope B, when I go from scope A and generate this data in scope A, using angular's ui-controller. Data is not available when the scope is initialized.
Note: I am fine with showing request data in the URL. I'm looking for the simplest way for new state to read data it needs and pass it to server and properly generate its contents.
When the page loads, it fetches data from server and populates scope "tests" with new data. This new data is shown on the page. I create links to scope "test" with this data. Links look like this:
<a ui-sref="test({id:test._id})">{{test.name}}</a>
On a rendered page it looks like this:
<a ui-sref="test({id:test._id})" class="ng-binding" href="#/test/57adc0e30a2ced3810983640">A test</a>
The href is correct and points to a database reference of an item. My goal is to have this reference as a variable in scope "test". My state provider:
$stateProvider
.state('tests', {
url: '/tests/',
templateUrl: 'test/index.html',
controller: 'Test.IndexController',
controllerAs: 'vm',
data: { activeTab: 'tests' }
})
.state('test', {
url: '/test/{id}',
templateUrl: 'test/item.html',
controller: 'Test.ItemController',
controllerAs: 'vm',
data: {
activeTab: 'tests',
testId: '{id}'
}
});
So far no matter what I tried I couldn't access "testId" in the "test" scope. It was either "undefined", created errors or returned "itemId: {id}".
My Item.Controller:
(function () {
'use strict';
function Controller(TestService) {
var vm = this;
vm.test = null;
function getTest(id) {
TestService.GetTestById(id).then(function(test) {
vm.test = test;
});
}
function initController() {
getTest(...);
}
initController();
}
angular
.module('app')
.controller('Test.ItemController', Controller);
})();
TestService provides http get methods for getting data from server.
(function () {
'use strict';
function Service($http, $q) {
var service = {};
function handleSuccess(res) {
return res.data;
}
function handleError(res) {
return $q.reject(res.data);
}
function GetTestById(_id) {
var config = {
params: {
testId: _id
}
};
return $http.get('/api/tests/:testId', config).then(handleSuccess, handleError);
}
service.GetTests = GetTests;
service.GetTestById = GetTestById;
return service;
}
angular
.module('app')
.factory('TestService', Service);
})();
I tried $scope - scope is not defined. I tried a number of other techniques, shown by other users with similar success - either "undefined" or error of some sort.
This is based on another person's code so there may be obvious mistakes, please let me know if you find any. If you need more code, let me know - I'll upload it to github (its a messy work in progress at the moment so I'm not sure what should be uploaded).
I am using Ionic framework for custom applications. In the process, I am trying to write Unit test for the factory datastoreServices which has a dependency on DomainService and $http. I am kind a confused on the implementation of Jasmine Unit tests.
My factories are as follows.
app.factory("datastoreServices", ["$http", function($http) {
return {
getData: function(data, DomainService) {
return $http.post(DomainService.host + 'factor', data);
}
};
}]);
app.factory('DomainService', function() { //here
if (ionic.Platform.isAndroid()) {
return {
host: 'http://10.0.2.2:7001/'
}
}
return {
host: 'http://localhost:7001/'
}
})
And my unit test skeleton is as follows. It has two dependencies so, couldn't figure out how to proceed. This is what I got so far for in unit test file.
describe(
'datastoreServices',
function() {
beforeEach(module('Myapp'));
describe('getData'),
function() {
it("Should return correct values", inject(function(datastoreServices, DomainService, $httpBackend) {
expect(datastoreServices.getData(httpBackend.. /***something here!**/ )
.toEqual("2.2");
}))
}
I have very little knowledge on mocking and stuffs. Can someone help me test that factory datastoreServices. The following things are to be tested:
Is Http post making correct calls?
Is the function returning correct promise?
Here is the similar scenario of app in plnkr.
Idk, if I am asking too much. Thanks in advance.
The key principles are:
$http is mocked during testing, meaning that your server is not being actually called during your test execution
you must use $httpBackend in order to assert http calls and mock server response https://docs.angularjs.org/api/ngMock/service/$httpBackend
you can easily inject or mock any dependencies needed for your test
Here's an example based on your OP code:
describe('datastoreServices', function() {
beforeEach(module('MyApp'));
// get a reference to the $httpBackend mock and to the service to test, and create a mock for DomainService
var $httpBackend, datastoreServices, DomainService;
beforeEach(inject(function(_$httpBackend_, _datastoreServices_) {
$httpBackend = _$httpBackend_;
datastoreServices = _datastoreServices_;
DomainService = function() {
return {
host: 'http://localhost:7001/'
};
};
}));
// after each test, this ensure that every expected http calls have been realized and only them
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('calls http backend to get data', function() {
var data = {foo: 'bar'};
// write $http expectation and specify a mocked server response for the request
// see https://docs.angularjs.org/api/ngMock/service/$httpBackend
$httpBackend.expectPOST('http://localhost:7001/factor', data).respond(201, {bar: 'foo'});
var returnedData;
datastoreServices.getData(data, DomainService).success(function(result) {
// check that returned result contains
returnedData = result;
expect(returnedData).toEqual({bar: 'foo'});
});
// simulate server response
$httpBackend.flush();
// check that success handler has been called
expect(returnedData).toBeDefined();
});
});
I am trying to unit test angularjs with QUnit but get the error messages: $httpBackend.whenGET is not a function, $httpBackend.when is not a function. I have included angular mocks and angular breeze service (http://www.breezejs.com/documentation/breeze-angular-service) which uses the angular q library for promises and httpbackend instead of $.ajax for data transmission. I am still unable to mock any of the calls to the server. Some sample code:
var $httpBackend,
injector;
var SPAModule = angular.module("spa");
injector = angular.injector(['ng', 'spa']);
$httpBackend = injector.get("$httpBackend");
SPAModule.config(function ($provide) {
$provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
});
test("WHEN the controller is called THEN it should be created with the correct data on the scope", function () {
'use strict';
// Given
$httpBackend.whenGET("/Breeze/Data/Jobs").respond({ data: jobData });
$httpBackend.whenGET("/Breeze/Data/Metadata").respond({});
var routeParams = { id: "b" },
// When
controller = injector.get('$controller')(toriga.propertyController, {
$scope: theScope,
$window: windowMock,
$location: locationMock,
$routeParams: routeParams
}),
$rootScope = injector.get('$rootScope');
$httpBackend.flush();
$rootScope.$apply(); // forces results of promise to be executed
// Then
notEqual(controller, null, 'controller was created properly');
strictEqual(theScope.pageTitle, "Property", "pageTitle was set on the scope");
notEqual(theScope.job, null, "Job set on the scope");
ok(toastrMock.warning.notCalled, "No warning messages were displayed");
ok(toastrMock.error.notCalled, "No error messages were displayed");
});
This code used to work fine when I was not using breeze but now I have switched I can't seem to get it to work and the documentation is poor on how to get this working. Any help would be appreciated.
I can't tell all of the details of your tests. I can offer some comfort that it does work .. and pretty much as you'd expect.
Here is an extract from the test/specs/lookups.spec in the "Zza-Node-Mongo" sample (it's in github) in which I replay through the $httpBackend mock a (subset of) the server’s response to a Breeze client request for "lookup" reference entities.
I'm using Jasmine instead of QUnit but I hope you get the picture.
// simplified for presentation here but materially sufficient
describe("when lookups service receives valid lookups data", function () {
var $httpBackend, flush$q, lookups
var lookupsUrlRe = /breeze\/zza\/Lookups\?/; // RegEx of the lookups endpoint
beforeEach(module('app'));
beforeEach(inject(function(_$httpBackend_, $rootScope, _lookups_) {
$httpBackend = _$httpBackend_;
flush$q = function() { $rootScope.$apply(); };
lookups = _lookups_;
}));
beforeEach(function () {
$httpBackend.expectGET(lookupsUrlRe).respond(validLookupsResponse.data);
lookups.ready(); // THIS TRIGGERS CALL TO FETCHLOOKUPS
$httpBackend.flush();
});
it("doesn't bomb", function () {
expect(true).toBe(true);
});
it("'ready()' invokes success callback", function () {
var success = jasmine.createSpy('success');
lookups.ready(success);
flush$q(); // NOTE NEED TO FLUSH $Q IN THIS TEST
expect(success).toHaveBeenCalled();
})
it("has OrderStatus.Pending", function () {
expect(lookups.OrderStatus && lookups.OrderStatus.Pending).toBeDefined();
});
... more tests ...
});
The "lookups" service (app/services/lookups.js) calls breeze to fetch lookups data from the server.
function fetchLookups() {
return breeze.EntityQuery.from('Lookups')
.using(manager).execute()
.then(function () {
logger.info("Lookups loaded from server.");
extendService(manager)
})
.catch(function (error) {
error = util.filterHttpError(error);
logger.error(error.message, "lookups initialization failed");
throw error; // so downstream fail handlers hear it too
});
}
As you might imagine, this is a pretty deep integration test that starts with a service consumed by a ViewModel and goes all the way through the Breeze Angular Service through $http just about to the network boundary before being intercepted by $httpBackend.