FAQ Database Discussion Community


how to fix images causing “karma WARN [web-server]: 404”?

karma-runner,karma-jasmine
I have an angular directive with a template that is doing something like: <img ng-src="{{url}}" /> In my test, I am setting the scope so that url points to a fictitious image... Karma then says: WARN [web-server]: 404: /fake.png So I go into my karma config file and add to...

Mocking a Service into Controller

javascript,angularjs,testing,jasmine,karma-jasmine
I'm trying to mock a service, with Jasmine 2.2.0: CheckoutService.patch() which returns a promise into my CheckoutController: describe('CheckoutController', function() { var $scope, vm, checkoutServiceMock, def; beforeEach(function(){ module('app'); checkoutServiceMock = jasmine.createSpyObj('CheckoutService', ['patch']); inject(function($rootScope, $controller, $q){ def = $q.defer(); $scope = $rootScope.$new(); vm = $controller('CheckoutController', { $scope: $scope, CheckoutService: checkoutServiceMock });...

Unit test controller with injected service

angularjs,unit-testing,jasmine,karma-jasmine
I want to test that my injected service is being called in my controller. login.controller.js angular.module('exampleModule') .controller('LoginCtrl', ['$state', 'AuthService', function($state, AuthService) { var self = this; self.submit = function() { AuthService.login(self.credentials) .then(function(res) { console.log('success'); $state.go('home'); }, function(res) { if (res.status === 400) { console.log('error') } }); }; } ]); login.service.js...

Accessing scope.variables inside a function in jasmine

angularjs,unit-testing,jasmine,karma-runner,karma-jasmine
I am trying to get the assert the value of the $scope.buttonDisable variable which is inside the save(). here is the test case describe('EditMeetingCtrl.save()', function () { var $rootScope, scope, $controller , $q , state , controller ; var companyService , meetingService ; beforeEach(angular.mock.module('MyApp')); beforeEach(angular.mock.inject(function (_$httpBackend_, _companyService_ , _meetingService_ )...

Angular Jasmine $httpBackend Response Tests

javascript,angularjs,karma-jasmine,httpbackend
I'm trying to test the response of an http call. The problem is, it passes no matter what response code I put in there or response data. Any ideas? Thanks! Controller.js $scope.getPresses = function() { var pressRequest = { method: 'GET', url: localAPI.url + 'press/', headers: requestHeaders }; $http(pressRequest) .success(function(data)...

Why karma isn't executing any tests?

javascript,jasmine,karma-jasmine,jhipster
I've created a JHipster project and created a javascript spec, however when I run karma start I'm getting this output: ~/projetos/consami/src/test/javascript$ karma start INFO [karma]: Karma v0.12.31 server started at http://localhost:9876/ INFO [launcher]: Starting browser PhantomJS INFO [PhantomJS 1.9.8 (Linux)]: Connected on socket -yuANSJ71nx8EeeomeZW with id 73836995 This is the...

WebStorm - Jasmine jQuery

jquery,unit-testing,karma-runner,webstorm,karma-jasmine
I'm quite new to the usage of WebStorm, but it's not working as epected. I had a project in the past, but now I try to recreate it and try to unit test my code. I'm very new to unit testing JavaScript code. So, I have a file karma.conf.js which...

Angular unit testing with Jasmine: how to remove or modify spyOn

javascript,angularjs,unit-testing,jasmine,karma-jasmine
AngularJS v1.2.26 Jasmine v2.2.0 How can I change or remove the behavior of a spyOn? When I try to override it, I get the following error: Error: getUpdate has already been spied upon var data1 = 'foo'; var data2 = 'bar'; describe("a spec with a spy", function(){ beforeEach(module('app')); var $q;...

ui.bootstrap breaks my unit tests with unexpected results error?

javascript,angularjs,unit-testing,karma-jasmine,ui.bootstrap
In the controller I've used ui.bootstrap to implement pagination on my page, after installing ui.bootstrap I got following error message on my unit tests Here is my Test file: 'use strict'; describe('LoginCtrl', function () { beforeEach(module('taxihomeFrontendApp')); var LoginCtrl, scope; var $httpBackend = {}; beforeEach(inject(function ($controller, $rootScope, _$httpBackend_) { scope =...

Karma testing lodash Factory

angularjs,jasmine,karma-runner,karma-jasmine,lodash
i have created a factory for the lodash library in my angular app like so: angular.module('lodash',[]).service('_', function(){ var _ = window._; // i am delete the _ property on the window // so that i m enforced to dependency inject // lodash each time i want to use it //...

Angular/Karma TypeError: Cannot Read Property 'offsetTop' of Undefined

javascript,angularjs,jasmine,karma-runner,karma-jasmine
I wrote an angular directive to manipulate the DOM on scroll and now I am trying to write a test in Karma/Jasmine but I am having trouble getting even a simple test to pass, but I haven't been able to find a solution I could apply to my situation. this...

Jasmine 2 custom matcher for hasClass in Protactor

jasmine,protractor,karma-jasmine
I upgrade my Jasmine 1.3 to 2.0 so I added a custom matcher to check css is present.Below is the code to check the matcher hasClass = function(actual,expected){ return actual.getAttribute('class').then(function (classes) { return classes.split(' ').indexOf(expected) !== -1; }); } But when I upgrade to Jasmine 2 then promise throws error...

How to inject a service to jasmine

angularjs,unit-testing,jasmine,karma-runner,karma-jasmine
I have the following test case MeetingCtrlSpec.js describe('ViewMeetingCtrl', function () { var $rootScope, scope, $controller ; beforeEach(angular.mock.module('MyApp')); beforeEach(inject(function ($rootScope, $controller ) { scope = $rootScope.$new(); $controller('ViewMeetingCtrl', { $scope: scope, }); })); it('should change greeting value if name value is changed', function () { //some assertion }); }); ViewMeetingCtrl.js (function ()...

jasmine spyOn on javascript new Date

javascript,angularjs,unit-testing,jasmine,karma-jasmine
I am unit testing the my client code in angulajs and i understand this code means var newdate = new Date(2013,6,29); spyOn(Date.prototype, 'getTime').and.callFake(function() { return newdate; }); we mockout the getTime() methode of the Date object. but i want to mock out the new Date() instead. for example the code...

How can I resolve a $q.all in my controller in a Karma unit test?

angularjs,q,karma-jasmine
My controller has: switchUserAccount: function() { $scope.model.currentMode = 'user'; console.log(ipCookie('currentPatientId')); $q.all([facilityCache.getFacility(), facilityGroupCache.getGroupList(), languageCache.getLanguageList(), genderCache.getGenderList(), raceCache.getRaceList(), dosingCache.getDosingOptions()]) .then(function(){ console.log('back from then'); cache.set('ui', 'adminPage', ''); cache.set('ui', 'schedulePage', 'patients'); if(ipCookie('currentPatientId')) { $location.path('/patient/view/' +...

Difference between browser().location().url() and browser().window().href() in Jasmine?

jasmine,karma-runner,karma-jasmine
Does anyone have ideas about the difference between browser().location().url() and browser().window().href() ? Thanks!...

Problems with $httpBackend.verifyNoOutstandingExpectation()

jasmine,karma-runner,karma-jasmine,jasmine-node
I have recently started writting unit tests using Karma + Karma-jasmine but I am having problems with the following tests: describe("WEBSERVICE:", function () { var webservice, $httpBackend, authRequestHandler, webserviceURL = "http://localhost:8006/"; beforeEach(inject(function (Webservice, $injector) { webservice = Webservice; $httpBackend = $injector.get("$httpBackend"); authRequestHandler = $httpBackend .when("GET", webserviceURL + "users/login") .respond(200, "ok");...

Unit Testing How to access object property

javascript,angularjs,jasmine,karma-jasmine
I have a simple angular service: app.service('myService', function() { this.getMsg = function (status, data) { var errMsg = ''; if (status.toString()[0] == 4) { if ((data.message.indexOf("3 tries left") > -1) || (data.message.indexOf("2 tries left")) > -1){ errMsg = "Opps, try later"; } else { errMsg = "Please try again."; }...

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

angularjs,jasmine,karma-jasmine,jasmine-jquery,angular-mock
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> <!-- include source files here--> <script...

Supress console logs from code being tested

jasmine,karma-runner,karma-jasmine
I'm unit testing a function which contains a console.log() call. How can I prevent the output of that call from being displayed in the output console of my test runner, in this case, Karma. I'm using Jasmine. I'm looking for a more elegant way than overriding browser's console methods, preferably...

spyOn could not find an object to spy upon for all()

angularjs,jasmine,karma-jasmine,jasmine-jquery
I'm getting the above error when I want to mock http REST services created using Restangular. Here's my piece of code: var someParameter = [{ "id": 1, "name": "Length" }] spyOn(Restangular, 'one').and.callThrough(); it('expect company service to be called', function () { httpBackend.expectGET('http://localhost:8283/com/companies', { someParameter: someParameter }).respond(mockToReturn); }); Has anybody encountered...

Unit testing angularjs directives's event broadcast

angularjs,unit-testing,karma-jasmine,angular-directive,angular-broadcast
I never had to test my angularjs directives before, also the directives I wrote for my current company is uses events to communicated directives to directives and services. And so I wrote a directive, e.g. a search directive. <m-search /> This directive broadcasts "searchbox-valuechanged" event and the key, now I...

Unit testing AngularJS Controller whilst following best practice

javascript,angularjs,unit-testing,karma-runner,karma-jasmine
We are building an AngularJS app following some of the best practice guidelines which are outlined here. Am specifically interested in testing a very simple controller to get up and running with karma. The controller code is: angular.module('ttn').controller('Login', Login); function Login(){ var login = this; login.title = 'foo bar content...

How to provide mock filters for unit testing

angularjs,karma-jasmine
I have a Controller that has this line of code var formattedDate= $filter('date')(dateColName,short); I am trying unit test this controller and I am not clear on how to mock the date filter in my code....

Testing a controller not using $scope using karma

angularjs,unit-testing,scope,karma-jasmine,controllers
I followed the instructions on docs.angularjs.org to test a controller with karma and it's perfectly working. However I was wondering if it's possible to test a controller which is not using $scope? Testing this controller is ok: angular.module('starter.controllers') .controller('PasswordController', function PasswordController($scope) { $scope.password = ''; $scope.grade = function() { var...

Testing Angular controller and spying on a mocked service

angularjs,unit-testing,jasmine,karma-jasmine
So I'm learning how to test in Angular and followed a tutorial that showed how to mock out the services that your controller uses. Can't seem to figure out why it isn't working so I'm turning here for help. Any advice on what I'm doing wrong and how to get...

Javascript Regex: “Any word” pattern

javascript,regex,testing,jasmine,karma-jasmine
In a Jasmine test, I am trying to set this match to fit with expressions like: 'Request <any_word> for <any_word> - Open actions menu'. However, it's not being possible with this line, but Javascript doc says that \\w is the regex for any word: expect(item.getIconToolTip()).toMatch('Request \\w for \\w - Open...

How to mock a window.location function in Karma/jasmine

angularjs,unit-testing,karma-jasmine
I would like to mock a functionality in Karma who returns a file after clicking a download button. I have the following AngularJS controller: var secure = angular.module('secure', []); secure.controller('ProcedureController', ProcedureController); ProcedureController.$inject = ['$controller', '$rootScope', '$scope', '$http']; function ProcedureController($controller, $rootScope, $scope, $http) { ... // Controller does more stuff var...

Call a controller function from Karma and Jasmine testing

javascript,angularjs,unit-testing,karma-jasmine
This is my angular controller :- angular.module('authoring-controllers', []). controller('NavCtrl', function($scope, $location, BasketNavigationService) { $scope.test= function() { $scope.testVar = BasketNavigationService.showBasketList(); }; }); TEST class describe('NavCtrl', function() { var scope, $location, createController; beforeEach(inject(function ($rootScope, $controller, _$location_) { $location = _$location_; scope = $rootScope.$new(); createController = function() { return $controller('NavCtrl', { '$scope': scope...

Nodejs : peerDependencies error while installing depedencNodejs

node.js,npm,karma-runner,karma-jasmine
In my attempt to get the libraries I need, npm install was working well till about a year and now as I move to a new server it breaks stating PeerDependencies error. I am kind of confused as I fail the reason for which the code is breaking, has any...

How to write unit test for http request?

javascript,angularjs,unit-testing,jasmine,karma-jasmine
I am trying to do an unit test a service in my case In my test controller myService.getItem('/api/toy/' + scope.id).success( function(toy) { $scope.toy = toys.details; } ); MyService angular.module('toyApp').service('myService', ['$http', function($http) { var service = {}; return { getItem: function(url) { return $http.get(url); }, }; } ]); Test file. describe('toy...

Angular Karma Testing $.cookie

javascript,angularjs,cookies,karma-jasmine,angular-cookies
My logout function sends a request to the logout api and clears all cookies effectively ending the session. It works really well but when I run the function in test, I get: ReferenceError: $ is not defined I know this comes from when, in the logout function, I try to...

inject gives throws Error: [ng:areq] Argument 'fn' is not a function, got string

angularjs,unit-testing,coffeescript,karma-jasmine
I am new to AngularJS and i try to develop an AngularJS app together with coffeescript in a testdriven way and cannot get inject to work. For creating the project i set it up using yeoman: yo angular --coffee someapp Then i created the test and the provider using yo...

Unknown provider: $angularFileUploadProvider <- $angularFileUpload in jasmine angular test

angularjs,jasmine,karma-jasmine
I have a directive on my angular module that I'm trying to write a test for. First off, I'm not clear how to even test this directive properly, but at this point, I'm getting the following error when karma runs the test. Unknown provider: $angularFileUploadProvider <- $angularFileUpload Here's my test....

AngularJS Jasmine Testing - How to Test AJAX Function That is Called on Controller Load

angularjs,jasmine,karma-jasmine
I have a controller that looks like: myApp.controller('myController', function($scope, myService){ $scope.myFunction = function(){ myService.myAJAXCall().then(function(data){ $scope.myVariable = data; }, function(){ console.log('failed call'); }); }; $scope.myFunction(); $scope.$watch('myVariable', function(newValue){ if(newValue === 'something'){ $scope.test = true; } else{ $scope.test = false; } }); }); $scope.myFunction() makes a AJAX call to an endpoint and sets...

AngularJS Karma testing “Error: Unexpected request: GET” doesn't seem to be executing request

angularjs,karma-runner,karma-jasmine
I have an AngularJS app that is having some issues in testing. Method PlanService.prototype.getPlanList = function() { this.activeRequest = true; return this.PlanFactory.planList().then((function(_this) { return function(response) { _this.plans = response.plans; return _this.activeRequest = false; }; })(this)); }; return PlanService; Unit test: var planService; beforeach(function() { module("notRealModuleName"); inject(function(PlanService) { planService = PlanService;...

angular empty $state name when testing routing with jasmine

javascript,angularjs,unit-testing,angular-ui-router,karma-jasmine
Like many folks, I'm new to testing Angular with Jasmine and am struggling to get this right. I use ui-router to do my routing and right now, the problem I'm having is that the $state.current.name in the test is an empty string and I have no idea why it does...

spyOn listener watch function not working

javascript,angularjs,jasmine,karma-jasmine,angularjs-watch
When I try to spyOn the listener function of a $scope.$watch, is like never call the spyOn http://jsfiddle.net/b8LoLwLb/1/ My controller angular.module('angularApp') .controller('MainCtrl', function ($scope) { $scope.name = ''; this.changeName = function () { console.log('the name has change to ' + $scope.name); }; $scope.$watch('name', this.changeName); }); My test describe('Controller: MainCtrl', function...

How do you access scope values (in your tests) on an Angular controller written in TypeScript?

javascript,angularjs,typescript,jasmine,karma-jasmine
If you write your angular controller in TypeScript in a way so that the controller accepts the $scope as input parameter: class TestCtrl { constructor($scope:ng.IScopeService) { $scope.myData = "Information"; } } you can easily verify properties on the scope in the following way from your tests: beforeEach(function() { $controller("TestCtrl", {...

How to test my http request in my app

javascript,angularjs,unit-testing,karma-jasmine
I am trying to write units test for my app and I have the following issue In my controller, I have something like $scope.test1 = function() { productFactory.getName() .then(function(products){ $scope.result = products; }) } productFactory angular.module('myApp').factory('productFactory', function($http) { var factoryObj = {}; factoryObj.getName = function() { return http.get(url) } return...

How to invoke spyOn on a scope function

angularjs,unit-testing,jasmine,karma-runner,karma-jasmine
I have the following jasmine spec. describe('ViewMeetingCtrl', function () { var $rootScope, scope, $controller , $q ; beforeEach(angular.mock.module('MyApp')); beforeEach(inject(function ($rootScope, $controller ) { scope = $rootScope.$new(); createController = function() { return $controller('ViewMeetingCtrl', { $scope: scope, meeting : {} }); }; })); it('the meeting type should be equal to an object',...

function is not being called with a karma spyOn

angularjs,unit-testing,karma-jasmine
My controller is: window.map.controller('ScheduleHomeController', ['$scope', '$location', '$route', '$routeParams', 'cache', 'patientCache', function($scope, $location, $route, $routeParams, cache, patientCache) { cache.set('ui', 'headerMessage', ''); if(cache.get('patient', 'currentPatient').patientId !== $routeParams.patientId) { cache.set('patient', 'currentPatient', patientCache.getPatient(parseInt($routeParams.patientId, 10))); } switch($route.current.originalPath) { case '/patients/:patientId/schedule': cache.set('ui',...

Karma testing with typescript and angular 2 is throwing Typeerror for “System.config”

javascript,unit-testing,typescript,karma-jasmine,angular2
I'm super new to testing, I'm using angular 2 as a new beginning to learning. ERRROR: INFO [Chrome 42.0.2311 (Mac OS X 10.9.3)]: Connected on socket xo5ufjmFKLGc5QSuAAAB with id 34336816 WARN [web-server]: 404: /base/jspm_packages/es6-module-loader.js ERROR [karma]: Uncaught TypeError: System.config is not a function at http://localhost:9876/base/js/angular.js?4c894ae47e8d04bb01965dbf22fa08aed20f0eb2:25575 ERROR [karma]: Uncaught ReferenceError: require...

ReferenceError: module is not defined (angular js unit testing with Jasmine)

angularjs,unit-testing,jasmine,karma-jasmine
I found a lot of questions about this, but the answers didn't work for me. I have a small controller in angular js. It works fine, and I wanted to start testing. I downloaded Jasmine standalone from here. I put my controller in the "src" folder, and another js file...

Reset broadcast() after each test case while using andCallThrough()

angularjs,unit-testing,karma-jasmine
I am using the code bellow to reset $broadcast after each test case, but it seems it $rootScope.$broadcast.reset(); doesn't function properly, since the test bellow should return 1, but it returns 6. Seems that the reason for this is andCallThrough(), since before I used it without andCallThrough() function, but after...

$http.get is undefined when $http is used outside angular code

angularjs,jasmine,karma-jasmine,angularjs-controller,angularjs-http
I am running jasmine unit test against a method which is outside angular controller. Running the jasmine throws the following error, TypeError: Cannot read property 'get' of undefined at testMethod Can anyone help me with fixing the above error. Thanks ! Test.js function testMethod() { var $http = angular.element('html').injector().get('$http'); $http.get('/testAPI/testCall').success(...);...

angularjs loadModules “should have a dummy test”

angularjs,jasmine,karma-jasmine,angularjs-module
Running karma unit tests for my project yields: Browser (OS) XYZ section should have a dummy test for XYZ FAILED minErr/<@../angular.js:63:12 loadModules/<@../angular.js:4141:15 forEach@../angular.js:323:11 loadModules@../angular.js:4099:5 createInjector@../angular.js:4025:11 workFn@../../vendor/angular-mocks/angular-mocks.js:2339:44 XYZ.spec: describe('XYZ section', function () { beforeEach(module('blah.XYZ')); it('should have a dummy test for XYZ', inject(function() { expect(true).toBeTruthy(); })); }); I notice that some states...

how to unit test a ngcontroller with external dependencies in jasmine?

angularjs,unit-testing,karma-jasmine
I am trying to write a karma unit test for a angularcontroller, this is the controller. Using a fileupload from here (https://github.com/nervgh/angular-file-upload): var c, di; c = function($scope, FileUploader, UploadHelper, currentUser) { var uploader; $scope.uploader = uploader = new FileUploader(UploadHelper.getOptions()); uploader.onSuccessItem = function(item, response, status, headers) { //do something };...

test to check ul elements and save in object

angularjs,protractor,karma-jasmine,karma-mocha
I am trying to write my first protractor test. I am looking for a directory listing and the numbers underneath it. I want to see what the numbers are with the department names in an object. I have this test but I am not sure what to do from here...

Using Karma, how do I exclude all files that match a pattern except for those within a specific sub-folder?

javascript,angularjs,karma-jasmine
I have a simple AngularJs application setup, that looks a bit like this: client vendor angular bootstrap jquery ... app.module.js app.controller.js ... node_modules angular-mocks ... I'm setting up a karma.conf.js file and I want to include angular\angular.js from vendor. I don't want to include anything else from vendor. Here is...

Error: No more request expected with Karma using Restangular from within a Service

angularjs,restangular,karma-jasmine,httpbackend
I have an AngularJS service and service name is User. I use it for authentication. Inside this service, I have an authenticate() function which uses Restangular to make a REST call to our API. It's perfectly working in my Angular application. I just started using karma so I can including...

The property andCallThrough() does not exist on the value of type jasmine.spy

jasmine,karma-jasmine
it('should call getCompany on the people service when getCompany is called', function () { spyOn(peopleService, 'requestPeople').andCallThrough(); scope.getCompany(); deferred.resolve(); scope.$root.$digest(); expect(peopleService.requestPeople).toHaveBeenCalled(); }); it('should populate the peopleList when getCompany is called', function () { scope.getCompany(); deferred.resolve(); scope.$root.$digest(); expect(scope.peopleList).not.toBe([]); }); I'm having a piece of code that mockes the service but I'm...

find element by css property that is not explicitly set

javascript,css-selectors,phantomjs,karma-jasmine
In order to disable chrome autofill I have added invisible user/password fields to my input forms: <!-- fake fields are a workaround for chrome autofill getting the wrong fields --> <input style="display:none" type="text" name="fakeusernameremembered"/> <input style="display:none" type="password" name="fakepasswordremembered"/> The problem is that this breaks tests like: expect(element.find('input').length).toBe(10); There are 12...

How can I unit test a controller in an AngularJS Directive?

javascript,angularjs,unit-testing,angularjs-directive,karma-jasmine
My directive is: window.map.directive('dosingFrequencies', [ function() { return { restrict: 'E', scope: true, templateUrl: '/views/directives/dosingFrequencies.html', controller: function($scope, util) { console.log('here we go!'); angular.extend($scope, { model: createModel(), addFrequency: function(med) { med.frequencies.push(createFreqModel()); }, removeFrequency: function(med, index) { med.frequencies.splice(index, 1); }, showTimeChecked: function(freq) { if (freq.showTime) { freq.prn = false; freq.quantity = '';...

Grunt Build Aborted Due to Warnings

angularjs,gruntjs,yeoman,karma-jasmine,yeoman-generator-angular
I'm new to angular and I'm working with Yeoman scaffolded apps and Grunt. I successfully created a few Grunt builds earlier on in the project but now when I do: Grunt build I get the following message: I'm not sure how to interpret the command line output which is below....

Setting global variables in jasmine for angularjs

javascript,angularjs,jasmine,karma-jasmine
I have an angular application with some global environment variables defined in an env.js file: (function(sp) { 'use strict'; pk.env = pk.env || {}; // localhost pk.env.baseUrl = 'http://localhost:8080/'; })(typeof exports === 'undefined' ? (this.pk = this.pk || {}) : exports); These variables are used in multiple factories to make...

Jasmine 1.3 to Jasmine 2.x cheat sheet

jasmine,upgrade,karma-jasmine,major-upgrade,jasmine2.0
I am migrating some unit tests from Jasmine 1.3 to 2.x and I was hoping there was a quick reference cheat sheet for some of the simple commands. Since I have not found one I thought it would be helpful to post what I have so far and others can...

confused with karma for testing an angularjs application

angularjs,unit-testing,karma-jasmine
I've been planning to study how to test my AngularJS app for more than 6 months now. Unfortunately, since I'm the only frontend developer, I've been so swamped with feature request. I'm unable to put time to doing unit-testing. However, I told the team during this Agile Sprint, I should...

Running AngularJS test for controller after changing $scope to this

angularjs,angularjs-scope,karma-jasmine,angularjs-controller
I am following the angularjs tutorial here : https://docs.angularjs.org/tutorial/step_02 My original controller: var phonecatApp = angular.module('phonecatApp', []); phonecatApp.controller('PhoneListCtrl', function ($scope) { $scope.phones = [ {'name': 'Nexus S', 'snippet': 'Fast just got faster with Nexus S.'}, {'name': 'Motorola XOOM™ with Wi-Fi', 'snippet': 'The Next, Next Generation tablet.'}, {'name': 'MOTOROLA XOOM™', 'snippet':...

Testing Ionic with Jasmine and Karma - Uncaught ReferenceError: angular is not defined

javascript,angularjs,ionic-framework,ionic,karma-jasmine
Long story short, when I run karma.conf.js I see Uncaught ReferenceError: angular is not defined I am starting to work with a pre-existing Ionic project.. and add some unit tests. Do I need to check our www/index.html .. I do not see angular.js included strangely enough.. is this the reason?...

Karma Test: PhantomJS: ReferenceError: Can't find variable: Audio

angularjs,html5,audio,phantomjs,karma-jasmine
I'm trying to use Karma and PhantomJS to test my app, and I'm getting the error: PhantomJS 1.9.8 (Windows 7) Controller: SongsCtrl should attach a list of awesomeThings to the scope FAILED ReferenceError: Can't find variable: Audio The offending line in my AngularJS Service is: var audio = new Audio();...

Jasmine - Testing if Controller Exists Getting Error

angularjs,jasmine,karma-jasmine,angular-mock
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 = _$rootScope_; $scope = $rootScope.$new(); $controller = _$controller_; $controller('RegisterController', {'$rootScope' :...

confused about testing $promise

angularjs,unit-testing,karma-jasmine
I'm testing out a controller which has a method that returns a json object from my server. I'm really confused on how to make expectations on what my method is returning. I need to do some cleaning up of my scope based on the results. What I'm trying to accomplish...

Invoking service method in Jasmine

javascript,angularjs,jasmine,karma-jasmine
Using Angular and Jasmine I would like to run the service method with some mockup data. Below is the code of my test which uses some working RoomsController trying to run test() method on the RoomsParamsSvc: describe('Rooms Controller', function() { var RoomsController, scope, location, httpBackend, RoomsParamsSvc; beforeEach(module('rooms', function ($provide, $injector)...

Angular Karma test not running properly, gives error “Argument 'fn' is not a function, got undefined”

javascript,angularjs,jasmine,karma-runner,karma-jasmine
I'm trying to add unit tests to an angular controller using karma but I've run into an issue and I need some help. I've found similar questions asked here but none have led me to an answer. I've tried changing the order of the "files" array in the karma.conf.js thinking...

Angular test using $httpBackend fails with “400 thrown” error

angularjs,karma-runner,karma-jasmine,httpbackend
For hours I've been trying to test my NewPostController with $httpBackend. The problem is whenever I set non-2xx status code in the response, the test fails. NewPostController has the following method: $scope.submit = function () { var newPost = $scope.newPost; PostService.insertPost(newPost).then(function (post) { $location.path("/my-posts"); }, function (status) { $scope.form.$setPristine(); $scope.error...

karma.conf.js automatic file ordering?

angularjs,jasmine,phantomjs,karma-runner,karma-jasmine
I have a large angularjs project ordered by features. I'd like to setup unit testing but I'm having trouble getting the karma.conf.js file ordering setup. I tried specifying a simple glob pattern like **/*.js but many of my modules failed to load due to the ordering that they're included in...

Karma + Angular undefined error

javascript,angularjs,unit-testing,karma-runner,karma-jasmine
I just started angular testing with karma and jasmine. I've written two basic tests. One of the two tests pass, but the other one is failing. I can't seem to debug it. I've been looking everywhere, and it should work according to various tutorials. The $scope variable should be available....

navigator.webkitGetUserMedia breaks unitTests with Karma/Jasmine

angularjs,unit-testing,karma-jasmine
I got a AngularJS WebApp, wich i test with Karma and Jasmine.js But it throws an error if i use navigator.webkitGetUserMedia() in my controller. TypeError: 'undefined' is not a function (evaluating 'navigator.webkitGetUserMedia') Here is a sample of my Controller app.controller('appCtrl', function ($scope, $interval, $location, globVal, loginService) { navigator.webkitGetUserMedia({video: true, audio:...

How to test if directive emited an event

javascript,angularjs,unit-testing,jasmine,karma-jasmine
I have this simple directive: ... var readyData = { caption: ctrl.caption, leftValue: ctrl.leftValue, rightValue: ctrl.rightValue, }; $scope.$emit($attrs.id + ".ready", readyData); //$scope is directive's scope and not $rootScope } and I have the following test: describe("Directive: summaryItem", function () { // load the directive"s module beforeEach(module("summaryItem")); it("Should emit the ready...

How to mock $scope.variables in jasmine

angularjs,unit-testing,jasmine,karma-runner,karma-jasmine
I have the following test case CompanyCtrlSpec.js describe('ViewCompanyCtrl', function () { var $rootScope, scope, $controller , $q ; beforeEach(angular.mock.module('MyApp')); beforeEach(inject(function ($rootScope, $controller ) { scope = $rootScope.$new(); createController = function() { return $controller('ViewCompanyCtrl', { $scope: scope, company : {} }); }; })); it('the company type should be equal to an...

In Karma Testing, ReferenceError: describe is not defined

javascript,angularjs,karma-jasmine
I was about to do unit test in my project. What I wrote was just a simple test code. However, there came out weird message : ReferenceError : describe is not defined. How can I get over this ? This is my code : 'use strict'; (function() { //Cal test...

Angular / Karma: unknown provider

angularjs,karma-jasmine
I am new to testing in Angular and finding difficult to understand how to do a simple test on my controller's injections, getting the error: Error: [$injector:unpr] Unknown provider: localStorageServiceProvider <- localStorageService Controller: angular.module('myApp.home', []) .controller('HomeCtrl', ['$scope','localStorageService',function($scope,localStorageService) { // ... }]); Test: describe('myApp.home module', function() { var $scope; var localStorageService;...

How would I test window prompts and confirms with Karma / Jasmine?

javascript,tdd,karma-jasmine,e2e-testing
I'm pretty new to TDD and I've been doing some programming prompts from reddit to learn it. This one is an acronym generator that asks for a string to be converted, displays it, and then asks if the user wants to generate another. My trouble is that I don't know...

scope.$watch does not get triggered after scope.$digest in karma unit test

javascript,angularjs,unit-testing,karma-jasmine
I want to test this directive: .directive('mwIcon', function () { return { restrict: 'A', scope: { mwIcon: '@', tooltip: '@', placement: '@', style: '@' }, template: '<i ng-class="iconClasses" style="{{style}}" mw-tooltip="{{tooltip}}" placement="{{placement}}"></i>', link: function (scope, el) { el.addClass('mw-icon'); //set icon classes scope.$watch('mwIcon', function (newVal) { if (newVal) { var isFontAwesome =...

Installing Karma failed

angularjs,npm,karma-jasmine
Tried to install Karma npm install -g karma A warning is produced npm WARN optional dep failed, continuing [email protected] At the end it seems there is no Karma installed karma init karma.config.js 'karma' is not recognized as an internal or external command (so a windows installation). However there seems to...

Karma exits with code 1 when it doesnt execute any spec tests

karma-runner,karma-jasmine,gulp-karma
Karma test runs fine but exits with code 1 if 0 of 0 tests are run. Does anyone know how to return exit code 0 and normally exit in this case? Using gulp-karma which fails the task when no specs are run.

display karma tests on browser

angularjs,unit-testing,karma-runner,karma-jasmine
I'm new to karma unit-testing angular. I tested angular-socket-io application. This is what I saw when I ran karma start on the console. 21:58 /tmp/angular-socket-io $ karma start INFO [karma]: Karma v0.10.10 server started at http://localhost:9999/ INFO [launcher]: Starting browser Chrome INFO [Chrome 40.0.2214 (Mac OS X 10.8.3)]: Connected on...

sinon server.autoRespond

javascript,ajax,karma-jasmine,sinon
I'm learning testing, so I construct this simple example, using karma,karma-jasmine and sinon.js: I have got an ajax Request, on success it sets an global variable. With the sinon fakeServer I fake the respond, everything is fine if I fire the respond with the sinon.server.respond() function manually. But changing the...

Jasmine: mocking $animate from Angular Material

javascript,angularjs,unit-testing,karma-jasmine
I am trying to mock the $animate service within a Jasmine unit test. The directive that I have under test is the following: angular .module('splashDirective', ['ngMaterial']) .directive('mAppLoading', ['$animate', function($animate) { var link = function(scope, element, attributes) { $animate.leave(element.children().eq(1)).then( function cleanupAfterAnimation() { element.remove(); scope = element = attributes = null; }...

When adding scope to the Angular-Seed default View Controllers the test suite now fails

javascript,angularjs,karma-jasmine,angular-seed
Using a fresh clone of angular-seed I am attempting some BDD and have added the following tests and code. However, once I add the $scope to the controller, the suite fails on the expect(view1Ctrl).toBeDefined(); expectation. Below is the only addition I've made and it causes the noted failure when Karma...

Angular Karma Test getting “TypeError: 'undefined' is not a function”

javascript,angularjs,karma-runner,karma-jasmine
Controller dashboardApp.controller('ExecutiveController', ['$scope', 'ExecutiveService', function ($scope, executiveService) { executiveService.getDashboardData().then( function success(response) { $scope.productsInfo = response.data; }, function error(reason) { console.log(reason); }); } ]); Test case for Controller 'use strict'; describe('ExecutiveController', function () { var scope, ctrl, mockService, $timeout; beforeEach(module('do.dashboard')); beforeEach(inject(function ($rootScope, $controller, $q, _$timeout_) { mockService =...

Error: Unexpected request: POST Karma-jasmine-angular

angularjs,unit-testing,jasmine,webstorm,karma-jasmine
the actual scenario is like when I am trying to test my angular js controller and service together in which first I call a get ajax request and on its success I call a user service which also contains a post ajax request. When I run test I got the...

Unknown provider in Karma test

javascript,angularjs,unit-testing,testing,karma-jasmine
I have the following provider: (function (angular) { angular.module('app') .provider('$_Config', ConfigProvider); function ConfigProvider() { .... //routes definition } ConfigProvider.prototype.$get = function () { return this; }; ConfigProvider.prototype.getRoutes = function() {...} //other prototype functions })(angular); In app.js I am using it like this: app.config(function ($routeProvider, $_ConfigProvider) { var routes = $_ConfigProvider.getRoutes();...

how to construct unit test for controller with $state?

angularjs,unit-testing,angular-ui-router,karma-jasmine
Trying to write a unit test for my controller: app.controller('StartGameCtrl', function ($scope, $timeout,$state) { $scope.startGame = function () { $scope.snap = false; $scope.dealCards(); debugger; $state.go('cpu'); } }); I wrote this jasmine unit test: describe('snap tests', function() { beforeEach(module('snapApp')); var scope, createController, state; beforeEach(inject(function ($rootScope, $controller,$state) { scope = $rootScope.$new(); createController...

how to mock $state.params in jasmine unit testing

angularjs,unit-testing,jasmine,karma-runner,karma-jasmine
I have the following controller EditMeetingCtrl.js (function() { 'use strict'; angular .module('myApp') .controller('EditMeetingCtrl', EditMeetingCtrl); EditMeetingCtrl.$inject = ['$rootScope', '$scope', '$state', '$http', '$translate', 'meetingService', 'companyService', 'notificationService', 'meeting']; function EditMeetingCtrl($rootScope, $scope, $state, $http, $translate, meetingService, companyService, notificationService, meeting) { $scope.meeting = meeting; $scope.companyId = $state.params.companyId; $scope.save = save; function...

My Karma spy is not picking up on my controller function

angularjs,unit-testing,karma-jasmine,spy
My spec: describe('ScheduleController', function() { var ScheduleController, scope, spies = {}; beforeEach(function() { module('mapApp'); return inject(function($injector) { var $controller, $rootScope; $rootScope = $injector.get('$rootScope'); $controller = $injector.get('$controller'); scope = $rootScope.$new() $controller('ScheduleController', { $scope: scope }); spies.buildScheduleUrl = spyOn(scope, 'buildScheduleUrl').and.callThrough(); }); }); it('should build a schedule url', function() {...

ANT task for calling Karma/Jasmine

javascript,angularjs,ant,phantomjs,karma-jasmine
While searching the internet it seems that Grunt is the preferred task runner for executing AngularJS test under Karma/Jasmine. Our project has server side java code and browser side javascript code. We already have a full unit test suite for the Java code, which we use ANT to run this...

Spy on a service method call using jasmine Spies

angularjs,unit-testing,jasmine,karma-runner,karma-jasmine
I have the following controller ViewMeetingCtrl.js (function () { 'use strict'; angular.module('MyApp').controller('ViewMeetingCtrl', ViewMeetingCtrl); ViewMeetingCtrl.$inject = ['$scope', '$state', '$http', '$translate', 'notificationService', 'meetingService', '$modal', 'meeting', 'attachmentService']; function ViewMeetingCtrl($scope, $state, $http, $translate, notificationService, meetingService, $modal, meeting, attachmentService) { $scope.meeting = meeting; $scope.cancelMeeting = cancelMeeting; function cancelMeeting(meetingId,...

AngularJS testing $resource - flush giving error

javascript,angularjs,unit-testing,karma-jasmine,angularjs-factory
I have a factory angular.module('RepServices', [ 'ngResource' ]).factory('Rep', function($resource) { return $resource('rep.do', {}, { get : { method : 'GET', params : { action : "fetchRep" }, isArray : false, responseType : "text" } }); }); and have created a test describe('RepService test', function () { var httpBackend; var repService;...

Angular 1.3 $parser validation method not passing test

javascript,angularjs,validation,jasmine,karma-jasmine
Recently, we upgraded from Angular 1.2 to 1.3. We still have to support IE8, so bar a few tweaks, everything mostly works. However, am having a strange issue with a validator failing unit tests, yet still working in real life. Also, it doesn't matter if I move it to $validators,...

configuration of karma/jasmine to test angularjs throws: No provider for “framework:jasmine”!

angularjs,unit-testing,karma-jasmine
Hello I'm trying to implement unit-tests for angularjs with karma and jasmine. I followed therefore this tutorial: http://tech.pro/tutorial/1473/getting-started-with-angularjs-unit-testing On the point Running Your First Test I get sucked because of an error: No provider for "framework:jasmine"! I googled for it and tried the suggested things like installing karma-jasmine and karma-chrome-launcher...