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

How to mock socket.io with Angular and Jasmine

Issue I’m having trouble figuring out how to correctly mock Socket.io in an Angular application using Jasmine and Karma. Here are the files found in karma.conf.js: ‘bower_components/angular/angular.js’, ‘bower_components/angular-mocks/angular-mocks.js’, ‘bower_components/angular-ui-router/release/angular-ui-router.js’, ‘bower_components/angular-socket-io/socket.js’, ‘bower_components/socket.io-client/socket.io.js’, ‘bower_components/angular-socket-io/mock/socket-io.js’, ‘public/javascripts/*.js’, ‘ng_tests/**/*.js’, ‘ng_tests/stateMock.js’ Here is how my controller

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

AngularJS and Jasmine: mocking services

Issue I am having trouble mocking the dependency of the following service “broadcaster” over the service “pushServices”. angular.module(‘broadcaster’, [‘pushServices’]); angular.module(‘broadcaster’).service(‘broadcaster’, [ ‘$rootScope’, ‘$log’, ‘satnetPush’, function ($rootScope, $log, satnetPush) { // .. contents .. }; }; The Jasmine spec is as

Continue reading

How to unit test (using Jasmine) a function in a controller which calls a factory service which returns a promise

Issue In the below SampleController, how do I unit test that postAttributes function calls sampleService.updateMethod. I’m having trouble since the updateMethod returns promise. angular.module(‘sampleModule’) .controller(‘SampleController’, SampleController); SampleController.$inject =[‘sampleService’]; function SampleController(sampleService){ this.postAttributes = function() { sampleService.updateMethod(number,attributes) .then(function(response){ //do something on successful

Continue reading

Angular services not being defined in beforeEach in Karma

Issue I have an Angular Application using Jasmine and Karma for testing. This is my testing class: var data = require(‘./user.mock.js’); describe(‘Service: UserService’, function () { var ServerUrl; var httpBackend; var userService; beforeEach(angular.mock.module(‘myModule’)); beforeEach(angular.mock.inject(function (_userService_, $httpBackend, _ServerUrl_) { userService =

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

Getting a `$digest already in progress` error when testing a `catch()` error handler

Issue This is my test: it(‘add.user() should POST to /users/, failure’, function() { mockBackend.expectPOST(“/users/”, {username:’u’, password: ‘p’, email: ‘e’, location: ‘loc’}).respond(400, {msg: “bad request”}); BaseService.add.user({username:’u’, password: ‘p’, email: ‘e’, location: ‘loc’}); mockBackend.flush(); }); afterEach(function() { mockBackend.verifyNoOutstandingExpectation(); mockBackend.verifyNoOutstandingRequest(); }); And when

Continue reading

Testing a Restangular responseInterceptor

Issue What is the best way to do a unit test on a Restangular responseInterceptor? For instance: .config([‘RestangularProvider’, function(RestangularProvider){ RestangularProvider.setDefaultHttpFields({cache: true, withCredentials: true}); RestangularProvider.addResponseInterceptor(function (data, operation, what, url, response, deferred) { console.log(‘response from ‘+ url); console.log(data); var extractedData; // ..

Continue reading

Angular httpBackend crashing browser

Issue When using Jasmine and Angular (1.4.7) with Restangular (1.4.0), httpBackend and angular-mocks (1.4.7), Chrome and PhantomJS both crash when encountering the following line: httpBackend.whenGET(‘/something’).respond(200); If I get rid of it entirely, as below, I get the following error: //httpBackend.whenGET(‘/something’).respond(200);

Continue reading

Jasmine test for ActivatedRoute Angular 7

Issue I am trying to write a simple test for ActivatedRoute. Here’s what my test looks like. it(“should check if subscribes are called in init”, () => { const subRouteSpy = spyOn(activatedRouteStub.paramMap, “subscribe”); component.ngOnInit(); expect(subRouteSpy).toHaveBeenCalled(); }); My TestBed config: const

Continue reading

Angular test 'subscribe is not a function'

Issue In my component inside ngOnInit I have a subscribe() inside which I call a component function: ngOnInit(): void { this.navigationService.itemReset$.subscribe(event => this.resetItem(event)); } in the navigationService I have: btnPressed$: Subject<Event> = new Subject(); itemReset$: Observable<Event> = this.btnPressed$.asObservable(); keyDown(event: Event):

Continue reading

testing directive with jasmine

Issue I have this directive but Im struggling with the jasmine test for it, any ideas? import { Directive, Output, EventEmitter, HostListener } from ‘@angular/core’; @Directive({ selector: ‘[ctrlKeys]’, }) export class CtrlKeysDirective { @Output() ctrlZ = new EventEmitter(); @Output() ctrlY

Continue reading

Angular testing switchMap call called 0 times

Issue In my Angular component I have this code: delete(post: PostInterface): void { const delete$ = this.appDataService.proxy .delete(post, this.paginate) .pipe(switchMap(() => this.loadDatas())); this.subscriptions.add( this.appDataService.start(delete$, ‘delete’).subscribe() ); } And I have this test: beforeEach(async () => { loadDatasSpy = spyOn(component, ‘loadDatas’).and.returnValue(of(paginate));

Continue reading

.detectChanges() not working within Angular test

Issue I’ve been tasked with writing tests for a chat app developed with Angular. Below is the snippet of Angular template code I’m currently writing tests for: <div class=”title-menu-container” fxLayoutAlign=”center center”> <button id=”save-title-button” mat-icon-button *ngIf=”titleInputEdit; else settings”> <mat-icon class=”secondary-text” (click)=”saveTitle(titleInput.value)”>check</mat-icon>

Continue reading

Angular unit test window.open can not find document

Issue In my codebase I am calling window.open and then after calling document.write function as follows. public launch() { const previewWindow = window.open(”); previewWindow.document.write( `<iframe width="100%" height="100%" src="${this.src}"></iframe>` ); previewWindow.document.body.setAttribute( ‘style’, ‘padding: 0; margin: 0; overflow: hidden;’ ); } But

Continue reading

How to change return value of jasmine spy?

Issue I’m using Jasmine to create a spy like so: beforeEach(inject(function ($injector) { $rootScope = $injector.get(‘$rootScope’); $state = $injector.get(‘$state’); $controller = $injector.get(‘$controller’); socket = new sockMock($rootScope); //this is the line of interest authService = jasmine.createSpyObj(‘authService’, [‘login’, ‘logout’, ‘currentUser’]); })); I’d

Continue reading

Mocking Observable of SpyObject in Jasmine

Issue My component subscribes to an observable of a service like that: ngOnInit(): void { this.sub.add( this.notesService.notes$.subscribe(notes => { this.notes = notes.map(note => { let profilePicture = generateProfilePicture(note.creator) return { …note, color: profilePicture.color, initials: profilePicture.initials } }) }) ); }

Continue reading

Mocking Observable of SpyObject in Jasmine

Issue My component subscribes to an observable of a service like that: ngOnInit(): void { this.sub.add( this.notesService.notes$.subscribe(notes => { this.notes = notes.map(note => { let profilePicture = generateProfilePicture(note.creator) return { …note, color: profilePicture.color, initials: profilePicture.initials } }) }) ); }

Continue reading