Issue I am trying to create a new Resource of the type Person in AngularJS. Once the resource is created, I would like to get the new resource id (which is returned by the server). it(‘should get the new Person
Continue readingTag: jasmine
Angularjs – simulate touch event in Protractor e2e test
Issue I use Protractor with Jasmine for my mobile Angularjs app. I want to test a touch event (touchStart / touchEnd etc…) on a particular element. Something like: it(‘should play video’, function(){ var poster = by.css(‘.video-poster’); element(poster).??? //Simulate touch event
Continue readingJavascript.confirm() and Angularjs Karma e2e test
Issue I have an Angularjs application that uses simple javascript confirm before executing some actions. Controller: function TokenController($scope) { $scope.token = ‘sampleToken’; $scope.newToken = function() { if (confirm(“Are you sure you want to change the token?”) == true) { $scope.token
Continue readinghow many instances for virtual machine started for protractor tests in sauce labs
Issue We were evaluating Sauce labs for our application. We were trying to get protractor tests run on multiple browsers at same time in Sauce labs. Will there be a new instance of VM created to run tests on each
Continue readingGetting the angular app to run when using protractor
Issue I must be missing something here … I’m trying to use protractor to run e2e tests for my angular application. The configuration file is something along the lines of: allScriptsTimeout: 11000, specs: [ ‘src/**/*.e2e.js’ ], capabilities: { browserName: ‘firefox’
Continue readingClicking an element inside repeater when another element equals specific input with protractor and jasmine
Issue My HTML structure is this: <li ng-repeat=”m in members”> <div class=”col-name”>{{m.name}}</div> <div class=”col-trash”> <div class=”trash-button”></div> </div> </li> What I want to be able to do is using protractor, click on the trash when m.name equals a specific value. I’ve
Continue readingProtractor testing a specific cell in ng-grid
Issue I need to locate and test a specific cell in an ng-grid table to ensure it’s not showing ‘NaN’. I have been able to locate cells in columns 1-7, but this cell is in column 14, which a user
Continue readingprotractor serial spec execution
Issue I faced with strange problem after my tests refactor. I deprecated everywhere beforeEach/afterEach blocks in order to significantly decrease execution time and now I have problems to run even simple specs one after another. I have create simple config
Continue readingRetrieve element within repeater in Protractor
Issue I’m sure this is a simple one but my eyes are slowly dying on me. Basically, is there a way to get an element within a repeater? For example, I have a bunch of anchors within a repeater, however
Continue readingProtractor – Page Object is not updating when the DOM elements are changed
Issue I am testing a SPA built with angular.js and im using Page Objects pattern to write my tests. In the app we have a number of lists that will be updated. For example there is a list of attachments
Continue readingHow I can write custom messages?
Issue I tried to find a good ways to create custom error messages in Protractor. And I found just three ways to do this: Use “jasmine-custom-messages”. But I don’t like this syntax: (I think that code looks pretty better if
Continue readingError: Timed out waiting for Protractor to synchronize with the page after 11001ms." when user browser.getCurrentUrl()
Issue I am testing login and logout functionality, below is my test cases it(‘should redirect to login page on click of logout’,function(){ signInPage.email.sendKeys(‘zahid.afaque@meltwater.com’); signInPage.password.sendKeys(1234); signInPage.loginButton.click(); expect(browser.getCurrentUrl()).toMatch(/\/collections/); signInPage.profileImage.click(); signInPage.logout.click(); browser.waitForAngular(); expect(browser.getCurrentUrl()).toMatch(/\/login/); }); When i run above test its failing and below
Continue readingJasmine: Expect does not get actual value
Issue This is second part of: Expect: does not get the actual value I was able to reproduce it a little bit better, so what I have: expect((rfpPage.buttons.sendRequest).getAttribute(‘disabled’)).toBe(‘true’); (rfpPage.inputs.firstName).sendKeys(‘Name’); (rfpPage.inputs.lastName).sendKeys(‘Surname’); (rfpPage.inputs.email).sendKeys(‘name@email.com’); (rfpPage.inputs.phone).sendKeys(‘1234312’); (rfpPage.inputs.company).sendKeys(‘Company’); (rfpPage.inputs.address).sendKeys(‘Leningrad Motorway’); (rfpPage.inputs.city).sendKeys(‘Moscow’); (rfpPage.inputs.postalCode).sendKeys(‘125171’); (rfpPage.inputs.eventName).sendKeys(‘Test Meeting’); expect((rfpPage.buttons.sendRequest).getAttribute(‘disabled’)).toBe(null);
Continue readingIsolation of actions and tests
Issue I try to refactor my code. I know that if I have several expectations they should be isolate in ‘it’. I try to understand how I can write instead this: describe(‘my scenario should make’, function () { var config
Continue readingUse Mock HTTP with Protractor and Jasmine
Issue How can I use Mock HTTP with Jasmine and Protractor ? In my test.spec.js, I declared a mock, but this mock doesn’t work. I don’t have any error. My api always responds and not the mock. I never see
Continue readingChaining element variables for better location in protractor
Issue In protractor I’m trying to clean up my locators, and organize things a little better. Currently, I have a variable that contains the element locator for a dialog, and a save button: var StoryPage = function(){ this.dialog = element(by.css(‘md-dialog’));
Continue readingProtractor: Async timing out, I think because it won't find an element
Issue UPDATE #2: Traced back to the web app using $timeout instead of $interval. Explained here http://www.protractortest.org/#/timeouts under waiting for page synchronization UPDATE: So I threw in browser.ignoreSynchronization=true; browser.sleep(5000);for the second test and it works. Not sure why…. The login
Continue readingDisable Jasmine expectation, like xdescribe or xit?
Issue On the Jasmine website I see that we can disable suites by xdescribe or individual specs by xit. Is there a way to disable only an expectation (like xexpect)? The reason why I’m asking this is because I’m writing
Continue readingHow to mock angular.module('myModule', []).value() in Jasmine/Protractor
Issue I’m trying to use Protractor’s addMockModule() to mock a simple AngularJS module and override a variable: Here is my HTML: <body ng-app=”myApp”> <div ng-controller=”myAppController”> Overriden module value <b>{{myValue}}</b> </div> <script src=”/Scripts/Lib/angular/angular.js”></script> <script src=”/module.js”></script> <script src=”/controller.js”></script> </body> Here is my
Continue readingTest login with protractor on a non angular page
Issue I am trying to use protractor for e2e testing but first I need to login on a non-angular page. I try to directly use the webDriver as indicated here but it fails. My e2e test: describe(‘angularjs homepage’, function() {
Continue readingProtractor, with isDisplayed() I get NoSuchElementError: No element found using locator
Issue In protractor 2.0, I am checking in a expect() if one element is displayed. I expect a false, but the weird thing is that I get following error: NoSuchElementError: No element found using locator: By.id(“userForm”) My code is: describe(‘closeModal’,
Continue readingExpected object to be a kind of ScalarObservable, but was Observable
Issue In my Angular application, I was using Observables in the following way: getItem(id): Observable<Object> { return this.myApi.myMethod(…); // returns an Observable } and I unit tested it: it(‘getItem(…) should correctly do its job’, inject([MyService], (service: MyService) => { const
Continue readingWhen does Jasmine .toHaveBeenCalledWith match the parameters?
Issue I have the following angular service and its jasmine test. The test calls f1() and spies on f2(). The function f2 takes variable v2 and modifies it (sets field a to 3). The function f2 should be called with
Continue readingangular 5 test static method of component
Issue I have a static method on my Component class that I am testing, my question is how it is possible to access that method within my spec testing file? So far I can access a component instance with: let
Continue readingTesting an HTTP request with retry() and HttpClientTestingModule
Issue I want to test an HTTP call error response with the HttpClientTestingModule. This works fine until I add a rxjs retry(2) to the HTTP call. Then, the test obviously complains that an unexpected request is found: Expected no open
Continue readingunit tests for component using utility class with static methods
Issue I have component which uses class LocaleService and static method of this service instant(). LocaleService in not injected into component. While testing the component I’m not interested in LocaleService internals and I don’t want to test it. Thus in
Continue readingAngular jasmine test not able to trigger Observable created with fromEvent rxjs operator
Issue I have a simple case. The standard AppComponent of an Angular app contains a ChildComponent which is defined in its own module ChildModule. The template of ChildComponent is very simple <div class=”child” (click)=”testClick($event)”></div> ChildComponent has an even simpler testClick(event)
Continue readingtesting angular template driven forms
Issue I am using angular 5, always the .controls property of the form is empty. Not sure why during testing angular doesn’t create the form controls by reading the template file. Template file <form #myForm=”ngForm” novalidate> <input #myCtrl required type=”input”
Continue readingAngular – 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 readingAngular Integration test: testing a function that is called when event from other component is emitted, how do I mock the event data?
Issue In my component A I have a function that updates the view based on data emitted from component B. I don’t want to integrate component B and make an actual even as that’s too complex for this test. I
Continue readingdefault spec file explanation that gets generated for component
Issue I created a component using ng generate component test and few files got generated. There is a file name test.component.spec.ts. It has this content. import { async, ComponentFixture, TestBed } from ‘@angular/core/testing’; import { TestComponent } from ‘./donations-pay.component’; describe(‘TestComponent
Continue readingJasmine spy is not overwriting mock implementation
Issue In the ngOnInit method of the class I am testing I call a function of a service which retruns an observable. I have implemented a mock for the service, but I’m trying to use a spy for this exact
Continue readingHow to wait for an xhr request in an angular test
Issue I have a component with a button. When the button is clicked, an HTTP request is made: this.tokensService.create(this.userInCreation).subscribe(nextCb, errorCb); How do I wait for this request to be completed? Using the async utility and fixture.whenStable does not help me.
Continue readingJasmine Testing Constructor That has a Promise
Issue I have a service that acts as a data-store. In it’s constructor, it attempts to “hydrate” the data-set from the device’s storage (using Ionic and it’s Storage service): @Injectable() export class SimpleDataStore { private _data: BehaviorSubject<any> = new BehaviorSubject<any>(undefined);
Continue readinghow to synchronise component state with html-input before assertion?
Issue I am trying to test interactions between a components internals and its HTML. In the following test code, I have an app-component with an input-field, which is linked to an attribute within the component using two-way binding. Test1 passes
Continue readingHow to inject Angular 6+ service variables into app-routing.module.spec.ts and test router redirection
Issue I’m trying to test whether a user is redirected successfully if an authenticated variable is set to true. I’ve tried injecting my LoginService into a beforeEach and setting the authenticated variable to false. Then, in the unit test, setting
Continue readingUnit Test for function with mat paginator method firstPage()
Issue I have a function I am trying to test. I am using the matPaginator.firstPage() method inside of it. However any test I write for this function I can an error of “Cannot read property ‘firstPage’ of undefined” I cannot
Continue readingTest adding class to the <body> in angular 7
Issue I have this root AppComponent that listenens for a change on a service, and then adds or removes a CSS class on the document.body import { Component, OnInit, Renderer2 } from ‘@angular/core’; import { SideMenuService } from ‘./core/side-menu/side-menu.service’; @Component({
Continue readingCatch console errors while running e2e tests with jasmine and protractor
Issue While running e2e tests (protractor, selenium) I want to catch any console errors and warnings generated by application. I know protractor plugin protractor-console-plugin which catches console and make tests fail but it prints all logs from all tests at
Continue readingHow to test angular data caching?
Issue I have an angular service that talks to our API. Certain requests for the same data can be cached locally to help things feel a bit faster. Here’s basically what’s going on in a service method that does some
Continue readingGet routerLink properties from HTML in Angular unit test
Issue I have following HTML property: <ul> <li class=”nav-item” routerLinkActive=”active”> <a class=”nav-link” [routerLink]=”[‘/home’]”>Home</a> </li> </ul> I want now to get the href as a value in the unit test. So far I have in my test-case: it(‘should navigate have login
Continue readingspyOn 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 readingTesting a RxJS Subject: subscribe method not getting called in the test
Issue I have a private Subject attributeNameSubject. There is a setAttributeName method that passes a string value to the subject. We get reference to that subject using the getAttributeName. I am trying to test the above code, but I always
Continue reading@angular-redux/store trying to test component that uses async on a property decorated with @select() – documentation does not exist
Issue I am trying to test a form that has a select form control with options that are iterated with ngFor with | async pipe on property ‘videoCategories’ decorated with @select() from the redux package. I can’t make that form
Continue readingAngular + Redux Jasmine testing "Cannot read property 'dispatch' of undefined" randomly thrown in runs
Issue I have an integration test that is dependant on 2 services which I am providing to the testbed with stubs. When I am testing a function updateCategory() in the subscribe block of this category I have a function ngRedux.dispatch({type:
Continue readingError 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 readingAngular Unit Testing – stub complex object
Issue In my unit tests, I have to create stubs that have a large number of properties. So I would have an interface like this: interface Person { id: string; name: string; age: number … } Then I will have
Continue readingimportScript and worker-html.js are failing jasmine/karma test cases
Issue Several of my test cases fail if I run them together. Individually they all pass. After adding some debug code in jasmine.js which otherwise was throwing object thrown error, I found that all the errors related to code similar
Continue readingAngular 8 Unit Test, Cannot set property 'valueAccessor' of null
Issue I’m trying to simply pass the test (should create – component=> toBeTruthy) for the custom component (angular component class) implemented with ControlValueAccessor. I’ve injected NgControl in constructor and pass the this keyword. constructor(@Optional() @Self() public controlDir?: NgControl) { this.controlDir.valueAccessor
Continue readingJasmine replace class while testing another class
Issue I have a plain old class, not a component, with this method that I want to test static fromJson(json: any): ClientDTO { const ret: ClientDTO = Object.assign(new ClientDTO(), json) const dp = new DateWithoutTimePipe() ret.contractStart = dp.transform(json.contractStart) ret.contractEnd =
Continue readingAngular testing – observable pipe is not a function
Issue I want to write a unit test for a photo-upload-mehtod. But I get the Failed: this.task.snapshotChanges(…).pipe is not a function TypeError: this.task.snapshotChanges(…).pipe is not a function Error. For the sake of simplicity of this question, I put the code
Continue readingDestroy undefined in Jasmine Test
Issue I am writing test cases for .ts file. when i run the command ng test its getting failed. I have tried to mock the destroy method inside beforeEach still getting failed. Component.ts export class DepComponent implements OnInit, OnDestroy {
Continue readingAngular component test error: TypeError Cannot read property 'subscribe' of undefined
Issue I have a simple unit test that is done using karma/jasmine on an Angular 6 component. From the pluralsight course and documentation I have gathered it appears I am mocking my service correctly that my component requires, but when
Continue readingAngular component test error: TypeError Cannot read property 'subscribe' of undefined
Issue I have a simple unit test that is done using karma/jasmine on an Angular 6 component. From the pluralsight course and documentation I have gathered it appears I am mocking my service correctly that my component requires, but when
Continue readingAngular 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 readingHow to test pending flag in Angular
Issue I have fetchBooks method that retrieve data from backend and then populates books variable. import { Component, OnInit } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html", }) export class AppComponent implements OnInit { isLoading: boolean; books; constructor(private booksService: BooksService)
Continue readingInitial value is stored in the variable after calling Angular Component method in Jasmine
Issue I have a component as follows: // customer-reservation.component.ts import {Component} from "@angular/core"; @Component({ selector: ‘app-customer-reservation’, template: “ }) export class CustomerReservationComponent { customerCount = 10; registerCustomer() { return this.customerCount++; } unregisterCustomer() { return this.customerCount–; } } Following is specs
Continue readingAngular Integration Testing – jasmine Spy – Can't mock a service method returning Observable
Issue I am new to doing integration testing. And the whole thing is so confusing. For my first test, Seems like my spying is not returning the data as i intend to return it. Gives and error: Expected 0 to
Continue readingHow do I unit test if an element is visible when the *ngIf directive is used using Jasmine in Angular
Issue I have an Angular 6 app and writing some unit tests trying to determine if an element is visible or not based solely on the boolean result of an *ngIf directive. Markup: <div class=”header” *ngIf=”show”> <div>…</div> </div> spec file:
Continue readingTesting angular component form for pristine is not working
Issue I have a form that has an input and I have a button that needs to be enabled only when the form data was changed. I am using a pristine check and it all works functionally in the browser
Continue readingAngular unit testing functions
Issue I have just started exploring unit testing in angular. I have a function in .ts file onValueChange(val: number): void { this.formGroup.get(this.controlName).setValue(val); } I am trying to test if the controlName has the value passed in the onValueChange parameters I
Continue readingAngular 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 readingAngular Routing Component Testing
Issue I am reading the official examples of angular routing testing from here . I didn’t understand how heroClick() does trigger click. it(‘should tell ROUTER to navigate when hero clicked’, () => { heroClick(); <——- how does this work !?
Continue readingMake test case for reusable mat table columns in jasmine
Issue This is my parent TS import { Component, Input, OnInit } from ‘@angular/core’; import { Column } from ‘../../../../shared/molecules/table/column’; import { DataRecord, TransitReport, } from ‘../../../organisms/transit-report-wrapper/transit-report.model’; @Component({ selector: ‘app-transit-report’, templateUrl: ‘./transit-report.component.html’, styleUrls: [‘./transit-report.component.scss’], }) export class TransitReportComponent implements OnInit
Continue readingHow to test component error handling with observable service
Issue Context I’m trying to test a component. In another post I asked about testing the direct function call. Here I’m focusing, using same example component, on the error handling of my component. I want to test, when my service
Continue readingAngular Unit Testing – How to trigger another emit from an injected service?
Issue I have a component that does the following: In the constructor, it takes the query parameters and parses them into the given quarter and year In ngOnInit, it subscribes to a service that returns a list of quarters and
Continue readingJasmine test for checkbox change handler function in angular 12
Issue I am trying to write simple test function for check box change, but I am unabled to run it. The error is Spec has no expectations. and the handler function is not covered in code coverage,. template: <input type="checkbox"
Continue readingJasmine test for checkbox change handler function in angular 12
Issue I am trying to write simple test function for check box change, but I am unabled to run it. The error is Spec has no expectations. and the handler function is not covered in code coverage,. template: <input type="checkbox"
Continue readingWhy checkbox checked property doesn't change after detectChanges()
Issue I try to change checkbox checked property by changing model but it doesn’t work. I cannot understand this behavior. Template: <input type=”checkbox” [(ngModel)]=”model”/> Testing Code: it(‘should be checked after click on unchecked checkbox’, () => { const checkbox: HTMLInputElement
Continue readingAngular test gives error – Failed: Cannot read property 'className' of undefined
Issue Below is my spec.ts. It runs fine and all the test cases are a pass. Somehowout of 3 times 2 times the test fails with the error Failed: Cannot read property ‘className’ of undefined. I never used className anywhere
Continue readingHow to unit test a nested if condition in with Karma-Jasmine in Angular?
Issue I have a function and I have a coverage of 75% with unit tests, however, I’d like to have a 100% of coverage of unit tests. This is the function: calculateRatingSummary(): void { if (this.averageRating > 0) { this.avgRatings
Continue readingAngular ngneat spectator service testing
Issue I am having trouble testing a service injected into an Angular component. Here is an example scenario I am facing. Let’s say I have SampleComponent that has SampleService injected. I want to test whether running handleAction() in SampleComponent calls
Continue readingAsync beforeEach finished before/after each test unit(it)
Issue Hey I am new to tests in angular 6(aka angular) and I have one concern regrading every test which I have seen so far. Let’s first look at a simple test of simple component(which is generated by cli) describe(‘CompComponent’,
Continue readingAngular how to test component methods?
Issue I’m new to Angular and i’m trying to learn how to write tests. I don’t understand how to mock and test methods from components. My HTML is the following: (You have a table with all your certificates. By using
Continue readingAngular 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 readingHow to run unit test case for toast message in angular service?
Issue I am working with an app based on Angular 12. I have service called notification service which handles toast messages from ngx-toastr library. This is how that service looks like: export class NotificationService { constructor(private toastr: ToastrService) {} showSuccess(message:
Continue readingHow to easily mock a service HTTP request with Jasmine (Angular)?
Issue Why wont this spy work? I am creating an instance of the prescriptionService and spying on the fetchClientPrescriptions method, but when I check to see if its been called, I get an error. Yet the first spy for getClientPrescriptions
Continue readingHow to cover Jasmine unit test for RxJS subject in angular
Issue I am very new Jasmine unit test cases. My scenario may be easy but I am not sure how to cover test case for ngInit for below class. Can someone help me, export class Component1 implements OnInit { details$:
Continue readingAngular2 unit test with @Input()
Issue I’ve got a component that uses the @Input() annotation on an instance variable and I’m trying to write my unit test for the openProductPage() method, but I’m a little lost at how I setup my unit test. I could
Continue readingExpect object length to be null
Issue I have the following Object where I need to test it to be null: getLastTeamUpdatedItemLogBuffer(): IBufferElement { const storageItems = this.storageSvc.getItem(StorageKey.lastTeamUpdatedItem, true) as IBufferElement; return storageItems || null; } Here is IbufferElement: export interface IBufferElement { timestamp: number; text:
Continue readingjasmine thorw ERROR: 'NG0303: Can't bind to 'options' since it isn't a known property of 'div'.'
Issue This is my html code. <div class="container" echarts [options]="Option"></div> When i run the testcase,throwing following error. Solution1 Above solution not recommencement. Do we have any other solution? Thanks in advance. Solution You have to import used modules: TestBed.configureTestingModule({ imports:
Continue readingHow to test private field in subscribe of dispatcher in Angular?
Issue I have file: @Component({ selector: ‘page’, templateUrl: ‘./page.html’, styleUrls: [‘./page.scss’] }) export class PageComponent implements OnInit, OnDestroy { private lts: Igst; constructor( private router: Router, private route: ActivatedRoute, private dispatcher: Dispatcher ) { this.dispatcher .ofType(ProductsPageActions.TILE_UPDATE_STATE) .pipe( map((action: ProductsPageActions.St) =>
Continue readingHow can I test elements wrapped in an ng-container exist for Angular 6 with Jasmine?
Issue I am trying to write a unit test to see whether or not elements wrapped in an <ng-container> exist, but my tests fails because it seems the elements are created any way. My code is: HTML <ng-container *ngIf=”router.url ===
Continue readingMocking Angulars ng-init function in a Jasmine test
Issue I would like to inject this function into the ng-init directive when I instantiate a controller in an angular test, in the html I would set it up like this: <div ng-controller=”my-ctrl” ng-init=”initialize({updateUrl: ‘list_json’}) In my test I could
Continue readingInject $log service on simple Jasmine test
Issue Yes, I’m completely new to Angular and Jasmine, and I can’t figure out how to inject a mock $log for my test. This is the test: (function () { ‘use strict’; describe(‘basic test’, function(){ it(‘should just work’, function(){ var
Continue readingAngular mock fails to inject my module dependencies
Issue I want to test an Angular controller for my application fooApp, defined as follow: var fooApp = angular.module(‘fooApp’, [ ‘ngRoute’, ‘ngAnimate’, ‘hmTouchEvents’ ]); … The controller, MainCtrl is defined: “use strict”; fooApp.controller(‘MainCtrl’, function ($scope, $rootScope, fooService) { … }
Continue readingCreate unit tests where each test has its specific test data and test mocks
Issue I have this test structure and it is working but It does not cover my requirements when I put more tests in this unit test .js file , but all related tests should go there. WORKING: ‘use strict’; describe(‘lessonplannerFactory
Continue readingangular resource promise catch, jasmine toThrow()
Issue I have some code in an angular controller: user is an angular $resource which returns a promise when the get method is called. $scope.credentials = { username:””, password:””, rememberMe:false }; var currentUser = {}; $scope.login = function(callback){ user.get($scope.credentials) .$promise
Continue readingAngular.mock.$interval.flush() throws strange exception
Issue I have created the following small controller for testing that the interval function is triggered at the specified interval angular.module(‘app’).controller(‘myTstController’, [ ‘$interval’, function($interval) { var called = 0; $interval(function() { called++; }, 10); this.getCalled = function() { return called;
Continue readingHow to Jasmine test code within angular module run block
Issue I would like to Jasmine test that Welcome.go has been called. Welcome is an angular service. angular.module(‘welcome’,[]) .run(function(Welcome) { Welcome.go(); }); This is my test so far: describe(‘module: welcome’, function () { beforeEach(module(‘welcome’)); var Welcome; beforeEach(inject(function(_Welcome_) { Welcome =
Continue readingkarma/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 readingAngular unit test for adding up values
Issue I’m new to angular unit test cases and I’m trying to write a unit test case for the following code that I have in my Angular controller. Data contains balance which is added up and assigned to $scope.Total .success(function
Continue readingHow 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 readingJasmine/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 readingJasmine – 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 readingAngularJS 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 readingIs it possible for jasmine to access the scope methods defined in an angular directive controller?
Issue I’m trying to unit test a directive like the one below. I want to be able to call the functions defined in the directive’s controller ($scope.save), but my tests can’t seem to access that scope at all. I also
Continue readingHow to check if location is changed and controller loaded
Issue I’m trying to write a unit test for a controller that does a POST then changes page. How can I check if a path is loaded and the controller for that path is loaded? Solution You can’t check that
Continue readingTesting Initialization of AngularJS Service with Mocks
Issue I am trying to test the way an angular service responds to the values it gets from another service when it is initialized, and I’m having trouble finding a non-clunky way of doing it… much less one that works.
Continue readingJSHint and angular-mocks error
Issue When i run JSHint over my Jasmine tests using angular-mocks, i get errors for the “module” or “inject” function. How can I fix this? I know i can define those methods as globals in the .jshintrc, but is this
Continue reading