Angular – Testing Routerguard

Issue I’m currently struggling on unit testing my canActivate() method from my Routerguard Service. The Service looks as follows: import {Injectable} from ‘@angular/core’; import {ActivatedRouteSnapshot, CanActivate, Router} from ‘@angular/router’; import {AuthService} from ‘../../auth/auth.service’; import {Observable, of} from ‘rxjs’; import {NotificationService}

Continue reading

Angular 8 Test – Devextreme Grid Child Nodes not Found

Issue I want to test a Devextreme Grid with Angular 8. Here is what my setup roughly looks like: HTML <dx-data-grid id=”grid” [dataSource]=”data”> <dxo-state-storing [enabled]=”true” type=”localStorage” storageKey=”storage-key”></dxo-state-storing> <dxi-column dataField=”field1″></dxi-column> <dxi-column dataField=”field2″></dxi-column> </dx-data-grid> Test describe(‘MyComponent’, () => { let component: MyComponent;

Continue reading

spyOn not working on a dependency in Angular 7 unit tests

Issue I have a component that depends on SearchAttributeService. There is a method called searchAttributeValidation service that returns a Subject. I am subscribing to that subject like this: attributeSearchValidation(): void { this._searchAttributeService.searchAttributeValidation.subscribe((value: string) => { if (value === this._searchAttributeService.emptyAttributeSearchData) {

Continue reading

Error in angular unit test cases: TypeError: this.userService.currentUser.subscribe is not a function

Issue I am getting this error while running angular unit test cases: Test Result SidebarComponent × should create TypeError: this.userService.currentUser.subscribe is not a function sidebar.component.spec.ts describe(‘SidebarComponent’, () => { let fixture: ComponentFixture<SidebarComponent>; let mockUserService; beforeEach(() => { mockUserService = jasmine.createSpyObj([‘currentUser’]);

Continue reading

Angular 8 Testing – Devextreme Grid getDataSource() not Working with State Storing

Issue I am writing an Angular 8 test that checks if a dx-data-grid correctly lists and renders the data. Here is what my setup roughly looks like: HTML <dx-data-grid id=”grid” [dataSource]=”data”> <dxo-state-storing [enabled]=”true” type=”localStorage” storageKey=”storage-key”></dxo-state-storing> <dxi-column dataField=”field1″></dxi-column> <dxi-column dataField=”field2″></dxi-column> </dx-data-grid>

Continue reading

Angular: Testing Http POST method

Issue I have a simple service method that does an http post call to add a todoList: add(event: any): Observable<TodoList> { let todoListToAdd: TodoList = { name: event.target.value, listItems: []}; return this.http.post<TodoList>("https://localhost:44305/todolist", todoListToAdd); } I want to unit test this

Continue reading

Angular Jasmine spy not being called

Issue I’m following the official Angular tutorial to test a component that calls an asynchronous service function: https://angular.io/guide/testing#component-with-async-service Creating the spy: const gardenSpy = jasmine.createSpyObj(‘GardenService’, [‘getGardens’, ‘createGarden’]); gardenSpy.getGardens.and.returnValue(of(testGardens)); … gardenServiceSpy = TestBed.get(GardenService); Configuring the TestBed to use my spy instead

Continue reading

Angular testing DOM elements with *ngIf

Issue Why does this test pass it (‘should hide datatable if data is undefined’, () => { component.DATA = undefined; fixture.detectChanges(); expect(fixture.debugElement.query(By.css(‘app-datatable’))).toBeNull(); }); but this doesn’t it (‘should hide datatable if data is undefined’, () => { component.DATA = undefined;

Continue reading

Angular Jasmine test case for navigation and getCurrentNavigation not working

Issue My component has both getCurrentNavigation and router.navigate I have implemented getCurrentNavigation from here Now page having constructor() { if (router.getCurrentNavigation().extras.state) { this.levelId = router.getCurrentNavigation().extras.state.arcadeSelectedGame; } } and navigation to another page const navigationExtras: NavigationExtras = { state: { dummyObject,

Continue reading

Angular how to test service methods?

Issue I’m trying to learn how to write tests. I don’t understand how to mock and test methods from services. My current service file is the following: import {Injectable} from ‘@angular/core’; import {HttpClient, HttpErrorResponse} from ‘@angular/common/http’; import {Observable, throwError} from

Continue reading

How do I mock $window injected manually in provider private function?

Issue I have the following provider: angular.module(‘MyApp’).provider(‘MyDevice’, function () { var ngInjector = angular.injector([‘ng’]), $window = ngInjector.get(‘$window’); function isMobileDevice () { return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/) .test($window.navigator.userAgent || $window.navigator.vendor || $window.opera); } this.$get = function () { return { isDesktop: function ()

Continue reading

karma/jasmine/angular toHaveBeenCalledWith is really called

Issue in my app for instance I’ve got $rootScope.$emit(‘loggedin’,data.user); $rootScope.$on(‘loggedin’, function(event,user) { console.log(‘called’); }); in my test spyOn($rootScope, ‘$emit’); var response = { “success”:1, “user”:{ “id”:1, “email”:”lama@test.test”, “fullname”:”Lama user”, “username”:”lamauser”, “groups”:[“Users”] }, “logged”:1 }; $httpBackend.when(‘POST’, ‘/api/v1/user’).respond(200,response); $scope.save(); $httpBackend.flush(); expect($scope.errors.length).toEqual(0); expect($rootScope.$emit).toHaveBeenCalledWith(‘loggedin’,response.user);

Continue reading

karma/angularjs how to test run block with an asynchronous service

Issue How can I test like: init.js lama.system module angular.module(‘lama.system’, []) .config([‘$httpProvider’, function($httpProvider) { // Crossdomain requests not allowed if you want do cors request see filter.php $httpProvider.defaults.headers.common[‘X-Requested-With’] = ‘XMLHttpRequest’; }]) .run([‘$rootScope’, ‘$state’, ‘$log’, ‘Global’,function ($rootScope, $state, $log, Global) {

Continue reading

Jasmine/Angular: TypeError: Cannot read property '$modules/$injector' of undefined

Issue I am trying to run jasmine test cases and i am landing on ‘$modules’ of undefined. I am loading unminified and latest versions of libraries as below, <script src=”lib/jquery-2.1.3.js”></script> <script src=”lib/jasmine-2.1.3.js”></script> <script src=”lib/jasmine-html.js”></script> <script src=”lib/boot.js”></script> <script src=”lib/angular-1.3.9.js”></script> <script src=”lib/angular-mocks-1.0.1.js”></script>

Continue reading

Jasmine – Testing if Controller Exists Getting Error

Issue i have a simple controller: app.controller(“RegisterController”, function ($scope, $location) { // Do something }); And all i am trying to do is to test this controller is defined: describe(‘RegisterController’, function() { var $rootScope, $scope, $controller; beforeEach(module(‘myApp’)); beforeEach(inject(function(_$rootScope_, _$controller_){ $rootScope

Continue reading

Testing $interval in Jasmine/ Karma

Issue I have a simple factory angular.module(‘myApp.dice’,[]).factory(‘Dice’, [‘$interval’, function($interval){ return { rollDice: function(){ return $interval(function(c){ count++; }, 100, 18, false, 0); } }; }]); In my test case I have describe(‘rolling dice’, function(){ var promise, promiseCalled = false, notify =

Continue reading

Controller is undefined in jasmine test

Issue karma.config.js: module.exports = function(config) { config.set({ basePath: ”, frameworks: [‘jasmine’], files: [ ‘node_modules/angular/angular.min.js’, ‘node_modules/angular-mocks/angular-mocks.js’, ‘node_modules/angular-translate/dist/angular-translate.min.js’, ‘browser/javascripts/*.js’, ‘browser/tests/*.spec.js’ ], exclude: [], preprocessors: {}, reporters: [‘progress’], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: [‘Chrome’], singleRun: false, concurrency: Infinity })

Continue reading

How to test $scope in Jasmine test?

Issue I trying to write unit tests for Angularjs with Jasmine. Here is my controller: function HomeController($scope, fav, news, materials) { console.log(‘home controller’); $scope.testMe = true; } module.controller(‘HomeController’, HomeController); And tests describe(‘Home controller tests’, function() { var $rootScope, $scope, controller;

Continue reading

Unit test controller

Issue I make an ionic app and it finish but when i start to add tests to it I face a problem with $resources ,in this case I have this Controller : .controller(‘newAccountCtrl’, function($scope, $window, $rootScope, API, $ionicPopup, $state) {

Continue reading

karma test returning validateAmount is not a function

Issue I’m trying to test scope function which will check due amount, but while running the test I’m getting validateAmount is not a function. app.js var ManagmentApp = angular.module(“ManagemntApp”, [‘ngRoute’, ‘angularModalService’, ‘ng-fusioncharts’]); ManagmentApp.config([‘$routeProvider’, function ($routeProvider){ $routeProvider.when(‘/’, { templateUrl: ‘templates/CandidateForm.html’, controller:

Continue reading