FAQ Database Discussion Community


Jasmine Unit Tests Unexpected this Reference

javascript,jasmine,jasmine-node
I am trying to test a fairly simple JavaScript function in Jasmine, however the first statement is throwing an error for being undefined. myClass.prototype.functiontoBeTested = function() { var x = this.method() ... } The above throws an error in Jasmine as method is not a function and is undefined. The...

How to manipulate verification on “text” in Webdriver by Jasmine JS?

javascript,node.js,webdriver,jasmine,protractor
I've already tried a lot of codes but nothing passed the tests. Usually the test is fail when it tried to read this verification or it receive "false" instead of "true". All the script is below: describe('LiveSite Portal - Client share a document ', function() { it('LiveSite - Home Page',...

adding a utility namespace in JasmineJS

javascript,jasmine
I'm starting to modify a JasmineJS test suite, and there are some logging calls I want to clean up. Specifically I want to add a utilities.js file in the directory of the test spec... and reference it throughout all my test specs. There are now two test specs testSuite1.spec.js and...

How to properly mock an Angular Promise returned from $http

javascript,angularjs,unit-testing,jasmine,angular-promise
I have been fighting with this for a little bit now and need some guidance. I would like to unit test this angular service... specifically, the failed part of the promise. (function () { angular.module('testable') .factory('myService', ["$http", "$q", function ($http, $q) { return { createThing: function(thing) { return $http.post("//...", thing)...

Mock the value of a service inside directive's unit test

angularjs,unit-testing,jasmine,karma-runner
Inside my directive's instantiation I have a call to a method that returns some data: data = myService.getData() and later in the code I am doing something = data[id] In karma I have an error, cannor read id of undefined, meaning that data is undefined. I tried to mock the...

How to call browser.get only once in a script?

javascript,angularjs,automation,jasmine,protractor
I am new to protractor, right now I am putting browser.get(URL) within the first 'it' statement and then for my afterEach statement I make the browser go back to the homepage. I am wondering if there's a better place to put the browser.get statement to make my tests more module?...

Testing angular controller with $resource and $promise using angular-text-patterns

angularjs,unit-testing,jasmine
I am following the angular-test-patterns guide, and I get it working with my first controller test. But when I write the next test, I get the error: TypeError: 'undefined' is not an object (evaluating '$scope.pages.$promise') The problem then I know is the following line: $scope.busy = $scope.pages.$promise; But I don't...

Testing Meteor packages with Velocity?

meteor,jasmine,meteor-velocity
Velocity is an amazing testing framework for Meteor and I am currently using it to test my application code. Now I added a local package to the app, but I don't know how (or if) I can test the package with Velocity, too. I would like to drop tinyTest in...

Trying to spy (Jasmine) on Array.prototype methods causes stack overflow

javascript,jasmine,prototype,spy,testem
This is pretty odd. Using the testem runner with jasmine2 and the following spec executes (though it correctly flags that there are no expectations): describe('Spying on array.prototype methods', function(){ it('should work this way', function(){ spyOn( Array.prototype, 'push' ).and.callThrough(); // expect(1).toBe(1); }); }); However, add an expect (any expect!) and it...

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,...

Why is my jasmine unit test not waiting for 'done'?

javascript,node.js,jasmine,jasmine-node
I have the test in my node application... it('will call done', function(done) { myObj.fn(function(){ done(); } }); and the code.... myObj.fn = function(success){ setTimeout(2000000000,success); } When I run the test I get this in the output... -MacBook-Pro:torus-pqdata user$ npm test > [email protected] test /Stuff/code bases/2015/torus-pqdata > jasmine-node specs/ However as...

get value/innerHTML/text of item produced with css locator

jasmine,protractor
I have something like: var items=$$('some css location'); console.log(items.count()); console.log(items.get(3).getInnerHTML()); console.log(items.get(3).getAttribute('text')); console.log(items.get(3).getText()); but all console.log calls return the objects itself with their functions,fields.. Is there a way to get the innerHTML/texts/values of the items without using expect? If I want to iterate the items and do some parsing over their...

How to execute jasmine tests for node modules from grunt

javascript,node.js,gruntjs,jasmine
I want to run some Jasmine 2.x tests for node.js modules in a Grunt build. My setup looks like this: src/foo.js exports.bar = 23; spec/foo.spec.js var foo = require("../src/foo.js"); define("foo", function() { it("exports bar as 23", function() { expect(foo.bar).toBe(23); }); }); With grunt-contrib-jasmine the node module system is not available...

Jasmine spyOn with multiple returns

javascript,angularjs,coffeescript,jasmine
I would like to test my angular application with Jasmine. So I created some tests, most of them work fine. But, one of my functions require the user to fill in an prompt. Tests can not fill this prompt, so I mocked them with spyOn(window,'prompt').and.returnValue('test'). This works, but only once....

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',...

How do I support jasmine and es6 syntax in Visual studio Code?

jasmine,ecmascript-6,vscode
Question where can I find and how do I add support for jasmine and es6 syntax in Visual studio code? ...

Testing an Angular directive using Jasmine 2's spyOn

angularjs,unit-testing,jasmine,spyon
I have an AngularJS directive I'm trying to test with Jasmine 2. Here's a Mock service that I have defined at the beginning my test. var Note = { getNotes: function (type, id) { console.log('I have been called') }, save: function () {} }; And here's my test: beforeEach(function ()...

'myApp.controller is not a function' error in Jasmine

angularjs,unit-testing,jasmine
I'm getting the following error in the js console log when attempting to assign the controller to 'myCtrl' variable in a jasmine test: 'myApp.controller is not a function' In the controller itself, the controller is defined as the following and this is what's triggering the error I mentioned: myApp.controller('myCtrl', ......

How to write jasmine test for following angular service which uses API and call backs

angularjs,callback,jasmine
In my AngularJS application, I am having trouble figuring out how to unit test the following code: This is the service being used by my test controller: angular .module('web.template') .factory('testService', testService); testService.$inject = ['$http']; function testService($http) { return { getTestDatas: function (callback) { var data = { 'testParams': "test" };...

How to solve error about “invalid selector” when using “if statement” in Protractor JS?

javascript,angularjs,node.js,jasmine,protractor
I want to use an invisible element as a condition if it present do X and else do Y. I've already tried to use by the class of this element as the locator and the ng-model and binding of him but none of them is worked :/ Please your assistance...

jasmine test run even before .click() is triggered

javascript,jquery,jasmine,jasmine-jquery
I am just playing with a basic ruby application which changes the html direction attribute upon clicking an button. Its working fine on the JQuery side but in my test case runs even when .click() is triggers. Here are my files. display.html.erb <p> <%= button_tag 'Convert', id: 'test', remote: 'true'...

Jasmine test a scenario when we are aborting a previous ajax request before making a new request and assigning it back to null after aborting

jquery,ajax,jasmine
I have a scenario of live search where i need to abort the previous pending ajax request before making a new one. Though I have written the below code and it works fine. App.MyNamespace.xhr = null; App.MyNamespace.makeAjaxRequest = function() { if (App.MyNamespace.xhr) { App.MyNamespace.xhr.abort(); App.MyNamespace.xhr = null; } App.MyNamespace.xhr =...

How to spy on another module in node with Javascript

javascript,node.js,jasmine,jasmine-node
I have this js module (simplified example): var dbLoader = require('dbLoader'); function MyModule() { this.build(){ return dbLoader.load('yipee'); } } module.exports = MyModule; How on earth do I spyOn(dbLoader,'load') ?? Because when I try I get the error spyOn could not find an object to spy upon for load() Any help...

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 [email protected]/angular.js:323:11 [email protected]/angular.js:4099:5 [email protected]/angular.js:4025:11 [email protected]/../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...

Protractor in Node: How do I order my tests to run synchronously?

node.js,selenium,jasmine,protractor
I'm wondering how to execute multiple "describe" blocks in synchronous order? describe('Go To Home Page', function () { browser.ignoreSynchronization = true; it("Url should be on Login Page", function () { browser.get(HomePageUrl).then(function () { browser.wait(urlChanged(loginPageUrl), 2000).then( function (newurl){ var url = browser.getCurrentUrl().then(function (url) { expect(url).tobe(loginPageUrl); //I know I'm at Login page...

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...

Jasmine false positive with {} and [] in jasmine-node

javascript,jasmine,jasmine-node
For some reason jasmine's... expect({}).toEqual([]); is reporting true (but they are different types). How do I do this check with jasmine?...

Testing local methods containing service calls using Jasmine

angularjs,jasmine
I am facing an issue with testing a local method in my Angular JS controller. I need to test retrieveRuleDetails method which contains a service call, but not able to proceed. Please help to test the below code: var retrieveRuleDetails = function(feeId, ruleId) { $rootScope.triggerLoading(true); FeesRulesService.getRule(feeId, ruleId) .then(getRuleSuccess) .catch(getRuleFail); };...

ReSharper's is not working with local paths

javascript,unit-testing,jasmine,resharper,qunit
I'm trying to reference some libs in qunit tests. When I'm using Resharper's /// <reference path="/Scripts/require.js" /> It produces the following reference in the html: <script type="text/javascript" src="reference/~/../MyProjectFolder/Scripts/require.js"></script> So reference is broken. I've tried different ways to specify path like absolute path, relative path, tried to start path with '~'...

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."; }...

“Test Finished” handler in Jasmine?

jasmine
How to add a Test-Finished handler to a jasmine test? I need it to deallocate resources consumed by the test. I'm using the very latest version of jasmine 2.3.1 with Node JS....

Protractor, with isDisplayed() I get NoSuchElementError: No element found using locator

javascript,angularjs,jasmine,protractor,angularjs-e2e
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', function() { it('should close the alert that appears after registration.', function(){...

Why is address undefined in my app?

node.js,express,jasmine,supertest
I have a simple express app: var express = require('express'); var path = require('path'); var app = express(); exports.app = app; var index = require('./routes/index'); app.use(express.static(path.join(__dirname,'client/dist/'))); app.get('/', index.get); function start(){ var port = process.env.PORT || 8080; app.listen(port, function(){ console.log('app is running on port: ' + port); }); }; exports.start =...

Mocking Angular $window in unit test cases

javascript,angularjs,unit-testing,typescript,jasmine
I have been trying to unit test my angular custom service written in Typescript. The service reads a global variable defined on the Window object. I have made it promise, so that in future I can make a AJAX call to get this information. Here is my stripped down service:...

Get error when try to use jasmine and angular

javascript,angularjs,jasmine,httpbackend
When I try to use $httpBackend.flush(); I get error TypeError: $browser.cookies is not a function. I can't find any information about this kind of error and any solutions. describe("someText", function() { var $httpBackend; var someManager; var authRequestHandler; var dataMockup = []; beforeEach(function(){ module('app'); inject(function($injector){ $httpBackend = $injector.get('$httpBackend'); someManager = $injector.get('someManager');...

How to test Express.js routes with Jasmine 2.3 and SuperTest

node.js,jasmine,supertest
I'm using Jasmine 2.3 installed via NPM and executed with Grunt. 'use strict'; module.exports = function(grunt) { grunt.initConfig({ package: grunt.file.readJSON('package.json'), exec: { jasmine: 'node_modules/.bin/jasmine' } }); require('load-grunt-tasks')(grunt); require('time-grunt')(grunt); grunt.registerTask('default', 'exec:jasmine'); }; I exported an Express.js application object and using it in my specs along with SuperTest. 'use strict'; var supertest...

_foo is not a function, when called from init method in Jasmine

javascript,jasmine
I am testing a controller which has a private method _init() called during its instantiation. It does some service calls (which are mocked out) and calls some private helper functions within the same controller. It all works great up until within a success block of a service call it tries...

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,...

Jasmine resolving promises after calls but before expects

jasmine
For testing my controller I have some services mocked out using $q injection. These will reject or resolve the promises where appropriate. My tests rely on spies to monitor if functions have been called. I've found all over that I need to call $rootScope.$digest() which works if I include it...

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 to specify http response order in angular js tests?

javascript,angularjs,unit-testing,jasmine
A controller makes 2 calls to a remote http location to get data. When data comes a procedure is called. When both requests return data, then data merging is done and some aggregation is performed. The purpose of a unit test would be to test if the controller works as...

Jasmine SpyOn haveBeenCalled on function reference don't work (Angular)

javascript,angularjs,jasmine
In my Angular controller I have implemented a listener, that call a function by reference: $scope.$on('$destroy', vm.popoverChooseProfile.remove); I have implemented a test with Karma and Jasmine. it('should remove the popover the scope is destroy', function() { var vm = createController(); vm.popoverChooseProfile = MOCK_POPOVER; spyOn(vm.popoverChooseProfile, 'remove'); $scope.$destroy(); expect(vm.popoverChooseProfile.remove).toHaveBeenCalled(); }); The test...

Reusing angular mocks in Jasmine tests using $provide

angularjs,testing,mocking,jasmine,karma-runner
I wish to reuse my mocks instead of having to set them up in every unit test that has them as dependency. But I'm having a hard time figuring out how to inject them properly. Here's my attempt at unit test setup, which of course fails because ConfigServiceMockProvider doesn't exist....

Expect fails for verifying inner HTML

jquery,selenium,testing,jasmine,protractor
For some reason my assert in protractor fails, what i'm trying to do is get the innerHTML (text) from an element: var stuff = $('css').html(); expect(stuff).toBe("Inner HTML Text here"); I verified that the $().html() yields the text i desire on the console, what is wrong with my expect statement? TypeError:...

How do I make direct server calls and verify returned data in a Protractor test?

angularjs,node.js,jasmine,protractor
I have a Protractor test for my Angular application that signs up a new user, logs into the app and then deletes the account. My app doesn't currently have "delete account" functionality in its UI. However, it does have an API to delete users. I have the following test that...

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...

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...

Is it possible to resolve promise within the 'executeScript'?

javascript,selenium-webdriver,jasmine,protractor,webdriverjs
I am trying to write my first test using Protractor+Jasmine for my non Angular application. I need call API function of my app global instance, get result and compare it in test. One of passed in parameters for this function is a callback which is called as soon as data...

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...

How to setup jasmine for typescript project

typescript,jasmine
I need some guidance of how to set up unit testing of TypeScript project with Jasmine. Test spec file looks like this: /// <reference path="../../../typings/tsd.d.ts" /> import {Mediator} from '../../../services/remoting/Mediator'; describe('Mediator', () => { let mediator: Mediator; beforeEach(() => { mediator = new Mediator(); }); it('blah blah', () => {...

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...

Testing Angular Controller with 'AS'

angularjs,unit-testing,jasmine
I would like to testing my controller, i have used 'controller as' in the app, now i am sh*ting myself over testing. Controller: (half of my controller) (function(){ angular.module('donateApp') .controller('MainCtrl', mainCtrl); mainCtrl.$inject = ['donateFactory', 'donateService', '$location']; function mainCtrl(donateFactory, donateService, $location){ var vm = this, checked = false; vm.submitted = false;...

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...

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...

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...

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 ()...

Injecting custom factory in jasmine test

angularjs,unit-testing,jasmine
I tried to inject a factory to my controller in jasmine test like in AngularJS - unit testing a factory that has dependencies When I $provide a factory in the test, I would expect the controller to use the provided factory. But the console.log still prints 'real value'. I don't...

Halt javascript execution until promise is resolved

javascript,angularjs,node.js,jasmine,protractor
I have a specific use case where in test code I want to fetch a tables headers (async) and then dynamically create getters on a javascript object. The syntax that I would like to use in my test is antenneTable.row(0).getAzimut();. The problem I am having is that antenneTable.row(0); returns a...

Using $injector in AngularJS when integration testing (without using ngMock)

angularjs,unit-testing,jasmine,integration-testing,karma-runner
I'm needing to setup some integration tests in AngularJS using Karma/Jasmine but having trouble, because when not using ngMock (since I want to hit the actual $http endpoints), there are no module or inject methods. So how do I inject services into my tests? I've tried angular.injector.invoke(...) but can't get...

How to make parts of Protractor wait or become synchronous?

javascript,selenium,jasmine,protractor,mocha
I have code like this in a protractor test, it goes to a home page determines we need to login and then calls this function. Note I'm running this in a NODE.js environment: function Login() { browser.findElement(by.id('ID')).then(function (ele) { ele.sendKeys('SomeUserName'); browser.findElement(by.id('password')).then(function (ele) { ele.sendKeys('SomePassword'); browser.findElement(by.partialButtonText('Sign in')).then(function (ele) { ele.click(); browser.getCurrentUrl().then(function...

How do I write a Jasmine test to verify that a callback does not raise an error?

javascript,asynchronous,jasmine,uncaught-typeerror
How do I write a Jasmine test to verify that an asynchronous callback does not raise an error? I am writing a function with this basic pattern: myFunction: function (callback) { this.doSomethingAsync(function () { if (callback) { callback(); } }); return "done"; } The parameter callback is optional. Thus, the...

E2E Protractor tests in firefox says 8 pending specs what does it mean?

javascript,selenium,jasmine,protractor,end-to-end
When I run my tests I get: 11 specs, 0 failures, 8 pending specs Finished in 56.861 seconds [launcher] 0 instance(s) of WebDriver still running [launcher] firefox #1 passed. What does this "8 pending specs" mean?...

Stubbing an angular service with a function that returns a promise using sinon

angularjs,jasmine,sinon
I'm trying to test a controller that calls a method on a service. The service method returns a promise, and the controller immediately invokes .then() inline after calling the service method. I'm trying to stub the service using sinon and Jasmine keeps throwing an error saying that then is undefined...

Why does Jasmine toEqual return true when comparing empty array with empty object?

javascript,tdd,jasmine
I get why the following returns false... expect({}).toBe({}); And I get why the following returns true... expect({}).toEqual({}); But why is the following true? expect([]).toEqual({}); ...

Testing nested React components

javascript,jasmine,reactjs,jestjs
I'm writing tests for my react application. But when I try to render a nested component, then I got the error TitleBar is not defined and the test fails. jest.dontMock('FUW.js'); jest.dontMock('TitleBar.js'); var React = require('react/addons'); var TitleBar = require('../js/components/TitleBar.js'); var FirstUseWindow = require('../js/components/windows/FirstUseWindow.js'); var TestUtils = React.addons.TestUtils; describe('First use wizard',...

Difference between injecting $scope and $rootscope into unit test?

angularjs,unit-testing,jasmine
This always confuse me and was wondering what, how, why, and when would we use either when writing unit tests. var $rootScope; beforeEach(inject(function(_$rootScope_) { $rootScope = _$rootScope_; })); vs var $scope; beforeEach(inject(function(_$scope_) { $scope= _$scope_; })); ...

Testing client side javascript code with Jasmine

javascript,jasmine
I have javascript code that looks like this: this.ProgressBarUpdater = { poll: function() { setInterval(ProgressBarUpdater.request, 5000); }, request: function() { $(".progress_bar_updater[data-url]").each(function(i, elem) { url = $(elem).data("url"); $.getJSON(url, function(data) { if (isFinished(data)) { location.reload(); }; $.each(data, function(key, val) { updateProgressBar(key, val); }); }); }); } }; isFinished = function(obj) { var...

Is it possible for jasmine to access the scope methods defined in an angular directive controller?

angularjs,jasmine,angular-mock
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 tried isolateScope(), but that didn't return the inner $scope object like...

Angular/Jasmine: $httpBackend.expectGET works on Mac, not on Linux

linux,angularjs,jenkins,jasmine,protractor
I have the following setup to test a directive: beforeEach(inject(function($compile, $rootScope, $injector) { $httpBackend = $injector.get('$httpBackend'); var html = '<password-strength-bar password-to-check="password"></password-strength-bar>'; scope = $rootScope.$new(); elm = angular.element(html); $compile(elm)(scope); $httpBackend.expectGET('l10n/en.js').respond({}); $httpBackend.expectGET('tpl/page_signin.html').respond({}); })); This works fine on a Mac. However, when I run the same code on Linux, it fails with the...

How to test a meteor method that relies on Meteor.user()

testing,meteor,jasmine
I am trying to determine the best way to test my code and am running into complications from every direction I've tried. The basic code is this (though far more complex due to several layers of "triggers" that actually implement this): Client populates an object Client calls a meteor method...

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", {...

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_ )...

Angularjs unit testing resolving promises

javascript,angularjs,unit-testing,jasmine,spy
I'm probably doing this wrong but I can't figure out how to fix it. I want to test a controller that uses a resource (ngResource) and I want to use a Spy as a test double for the resource so it doesn't actually do the http call. In the code...

Javascript Kriskowal Q JS promise not working

javascript,jasmine,q
I have created a promise using kriskowal/q module but when i try to use this it does not go into any function either happy path or error path. here is my promise creation class var Q = require('q'); var Test = function () { }; Test.prototype = (function () {...

Retrieve element within repeater in Protractor

angularjs,jasmine,protractor,angularjs-e2e,e2e-testing
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 the class attached to the anchor is generic, so something like:...

Protractor, Done and Expect, why do we need wait?

selenium,selenium-webdriver,jasmine,protractor
I thought Done would make things run synchronously, meaning after I click a link, the click call back would happen after the click, apparently not as this doesn't work. browser.ignoreSynchronization = true; var firstURL = "https://www.google.com/?gws_rd=ssl"; describe("test", function () { browser.get("http://www.google.com"); it("Should be on google url", function () { expect(browser.getCurrentUrl()).toBe(firstURL);...

Jasmin-Karma and mocking localStorage spyOn could not find an object to spy upon for getItem()

angularjs,unit-testing,jasmine
I am currently evolving into TDD and want to test my AuthController. Inside my controller there is a service being injected, called AuthService. This service uses $localStorage, respectively the ngstorage bower package. I want to mock it in order to test my controller. I did so by using SpyOn provided...

Given a list of links, how do I click and validate each one using C# or Protractor, with Selenium?

javascript,c#,selenium,jasmine,protractor
Code below is in C#, but I also know javascript/protractor. Looking for any pattern that works. var links = driver.FindElements(By.TagName("a")); foreach (var ele in links) { if (ele.Displayed == false) continue; if (ele.Enabled) ele.Click(); System.Threading.Thread.Sleep(3000); driver.Navigate().Back(); System.Threading.Thread.Sleep(3000); } Without the sleep above (which I don't like) the page hasn't settled...

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...

How to synchronous test animation in AngularJS 1.3.15?

javascript,angularjs,tdd,jasmine
I guess I have a migration issue with angular-animate.js from version 1.2 to 1.3. Here is my animation 'use strict'; angular.module('cookbook', ['ngAnimate']) .animation('.slide-down', function() { var NG_HIDE_CLASS = 'ng-hide'; return { beforeAddClass: function(element, className, done) { alert('before add'); if(className === NG_HIDE_CLASS) { element.slideUp(done); } }, removeClass: function(element, className, done) {...

Angularjs: Testing controller function, which changes $scope

angularjs,testing,jasmine
I'm trying to test this controller function: $scope.deleteAccount = function(account) { Account.deleteAccount(account._id) .then(function() { angular.forEach($scope.accounts, function(a, i) { if (a === account) { $scope.accounts.splice(i, 1); } }); }) .catch(function(err) { $scope.errors.other = err.message; }); }; It is on a admin page. The function calls the factory (with promise) and the...

Jasmine async tests inside loop are not working as expected

javascript,node.js,unit-testing,jasmine
I have written some unit tests for a node.js driven API I built using Jasmine. The tests work fine, but now I would like to run a set of async tests with different inputs, but I cannot get it working. My tests run some requests against the API with an...

FireFox doesn't switch to a non-angular popup window by Webdriver JS (via Protractor)

javascript,node.js,webdriver,jasmine,protractor
i can't switch windows during my testing by Selenium Webdriver using Jasmine JS On FireFox browser (latest v) Runner: Protractor JS Platform: Selenium Webdriver on Node.JS Code framework: Jasmine JS The code is below: describe('LiveSite Portal - Client pay by PayPal', function() { afterEach(function () { browser.ignoreSynchronization = false; });...

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...

Testing modal.open() using Jasmine

javascript,angularjs,jasmine
So this is my $scope function. I want to test this by Jasmine. $scope.viewIndividualDetailsByTitle = function(details){ $modal.open({ templateUrl: 'components/content-management/content-assessment/partial/title_detail.html', controller: 'ContentAssessmentTitleDetailCtrl', size: 'lg', backdrop: 'static', resolve: { cpPortfolioTitle: function(){ return details; } } }); }; This is what I wrote in Jasmine. describe('Ctrl: ContentAssessmentCtrl', function(){ beforeEach(module('cmsApp')); var ContentAssessmentCtrl, scope, modal,...

Inconsistent behaviour with browserstack testing of ReactJS via travis-ci vs localhost

jasmine,reactjs,karma-runner,travis-ci,browserstack
I'm running test towards browserstack with karma (karma-browserstack-launcher, browserify + reactify), using jasmine as test suite with my reactjs code, and I'm getting inconsistent behaviour. If I run karma start karma.conf from my laptop (using Chrome 39 on windows 8.1), every test runs fine, but if I the command is...

Unit Test Angular http.post with Data in Header

angularjs,unit-testing,jasmine,angular-http
I am trying to write a unit test for service that performs a http.post to an api that passes credentials in the header. Controller: app.controller('LoginController', function($scope, $http, signInService) { $scope.LogIn = function(usrnm, pwd) { signInService.authUser(usrnm, pwd) .success(function (data, status, headers, config) { // Display success message $scope.gotToAddress = data.successUrl; })...

How to use Jasmine and CucumberJS with Protractor

angularjs,testing,jasmine,cucumber,protractor
I'm looking to use Protractor, CucumberJS, and Jasmine for testing my project. How do I use both Jasmine and CucumberJS with Protractor? Here's the project setup I've created: /path/to/myproj/protractor.conf.js exports.config = { seleniumServerJar: 'node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar', specs: [ 'features/*.feature' ], baseUrl: 'http://localhost:8080', multiCapabilities: [ { 'browserName': 'chrome' } ], allScriptsTimeout: 380000, getPageTimeout:...

How to close a native web browser popup in Jasmine JS?

node.js,google-chrome,selenium,jasmine,protractor
How to close a native web browser popup in Jasmine JS? I can't succeed to close this dialog and it keep showing up in all the running. Please your help! The code: describe('LiveSite Portal - Client perform a call', function() { it('LiveSite - Home Page', function() { liveSiteHome(); }); it('LiveSite...

Unexpected variable type when testing isolate scope with Jasmine

javascript,angularjs,jasmine
I am testing a directive with isolate scope (angular) and Jasmine test framework. Everything is working fine with one oddity: if I change the variable type on $scope from string to number, Jasmine continues to see it as a string even though the directive code itself properly treats it as...

Jasmine - correctly mocking an object with a constructor

javascript,angularjs,unit-testing,mocking,jasmine
I'm trying to mock the native WebSocket in a jasmine test for Angular, I can spy on the constructor and send function, but I can't figure out how to spoof a call of onmessage. WebSocket is extracted to an Angular constant: webSocket. My test looks like this: describe('Data Service', function...

Testing variable binding using Controller As syntax

angularjs,jasmine,angularjs-controller
I'm trying to test a simple form controller using the controller as syntax. What I want is to be able to pass in different field values to each unit test and see how the controller reacts. The code I'm using as an example: Controller: angular.module('auth').controller('LoginFormCtrl',['AuthService',function(AuthService) { var self = this;...

AngularJS jasmine factory tests with spy

angularjs,jasmine
I have an account and user factory. Now I want to test the account Factory. In the test I want to check whether new User() was called and fake data is returned. angular.module('app') .factory 'Account', [ 'User', (User) -> class @Account constructor: (account) -> @self = this @user = new...

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...

Jasmine beforeEach not called

javascript,unit-testing,jasmine,jasmine-jquery
Just starting with Jasmine and following the instructions on the Jasmine website for async testing I notice the beforeEach function is never called. Any idea why not? I don't find any hints relevant anywhere on the web. Thanks. Code The code is really simple: describe("Testing test.php", function() { it ("Gets...

Node.d.ts issues errors using typescript compiler, how do I fix?

node.js,visual-studio,typescript,jasmine,protractor
I have a project that's a NODE console application project using Visual Studio 2013. When I compile the solution I'm getting typescript errors as follows: Typescript wants a semicolon after export interface ReadableStream extends EventEmitter { readable: boolean; read(size?: number): string|Buffer; //Like this ----> read(size?: number): string;|Buffer; Which means I...

Jasmine2 Stacktrace

jasmine,protractor,stack-trace,jasmine2.0
When we run our Protractor tests with the jasmine2 framework we get rather useless stack traces such as the following. These are sporadic and never in the same place twice. I can re-run the tests and it'll work just fine. What exact causes this type of error and how can...

How can I call external JS from another JS by Protractor JS?

javascript,node.js,selenium-webdriver,jasmine,protractor
I'm using Jasmine as my JS framework to my automated test scripts. I want to call another JS file from another test script. Something like: describe('call JS Testing', function() { var exScripts = function(script){ exScripts.src = 'c:\\automation\\tests\\'; }; it('call to script', function() { exScripts('onboarding.js'); }); }); Is it possible to...

Jasmin spy listens on AJAX Cannot read property 'done' of undefined

javascript,jquery,ajax,jasmine
I am trying to check if data gets sent to the server by spying on jQuery’s ajax method. Everything works until I add a 'done' function to the ajax post. The error I get from Jasmine is: TypeError: Cannot read property 'done' of undefined Jasmin spec: describe("Post New Project Definition",...

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...