How can I see what karma sees when I use browser().navigateTo() - angularjs

I am just getting started with karma, and although it seems that everything is hooked up properly and my unit tests are being run as expected, I can't get my end to end tests to find any elements.
When I go to the debug page, I can see a very brief flash of my application, which says to me that my proxy and config in general is hooked up properly, but when I run
describe('my app', function() {
beforeEach(function(){
browser().navigateTo('/');
});
it('should display the home page', function() {
expect(element('title').text()).toEqual('my title');
});
});
it never finds an element, no matter the selector I put in.
My question, though, is... is there some way that I can see what it is seeing? Can I get karma to dump the full text of the html response? If I could do that, I could at least see what it is getting back. As it stands, I am getting no debugging information at all and it is kind of frustrating.
Feel free to ask for more information if I can make it easier to answer the question. Thank you for any help you can provide.

You can use pause() inside your test to pause the execution, then you can resume from the UI.
The docs for pause() are here.
You can also use sleep(seconds) to make a timed pause, if you want to auto resume.

Related

Waiting for the click event in PhantomJS 2 with Jasmine 2.x and AngularJS

I am trying to test an Angular directive that uses the click event and getting nowhere. I can get the event to fire just fine, but PhantomJS2 just takes forever to make the event happen and I can't figure out a way to get Jasmine to wait for it to happen before running the assertion. I've searched quite a bit and the most common response is this: How to wait for a click() event to load in phantomjs before continuing?. Sadly, that guy hasn't figured it out either, and I'm not waiting for a page to load, just for the click event to finally register. I'm hoping that someone else has and just didn't see that question or didn't want to start a reply on such an old question. For reference, the directive in question selects the text within an input tag if there is none already selected. I've tried every permutation of timeouts that I can think of, but nothing works. The last attempt involved using the done() function from Jasmine, but still no luck.
//the default value in the input is "unchanged"
it('should not select anything if there is already a selection in the element', function(done) {
element[0].setSelectionRange(2, element[0].value.length);
element.triggerHandler('click');
scope.$digest();
expect(theWindow.getSelection().toString()).toEqual('changed');
done();
});
All reasonable suggestions will be considered. I'd be ecstatic if someone had a link to a solution that I somehow didn't find with my Google-foo.
Note: I got the idea about using setTimeout from here: https://newspaint.wordpress.com/2013/03/19/how-to-click-on-a-div-or-span-using-phantomjs/

Non-angular page opened with click - angular not defined using ignoreSynchronization or waiting for Angular without

After a lot of research, and tinkering, I can't seem to actually get my Protractor test to do anything else other than have an Angular related error, even though I am using browser to avoid Angular being detected at all.
The test involves an Angular app, opening a dropdown in it, and clicking on the link for the console; the console opens a non-Angular admin page in a separate window.
So based on the many informative SO posts I found, I first used this...
browser.driver.getAllWindowHandles().then(function(handles) {
browser.driver.switchTo().window(handles[1]).then(function() {
//expect for new window here
});
});
Which appeared to work, as I could get to the window through repl pretty easily.
The issue is when either of the following were added...
browser.driver.getAllWindowHandles().then(function(handles) {
browser.driver.switchTo().window(handles[1]).then(function() {
expect(browser.getLocationAbsUrl()).toContain('/console/login.jsp');
expect(browser.driver.findElement(By.css('th.login')).getText()).toEqual('Login');
});
});
One expect check the URL and the other checks for the header element on the page, which is a table header. When I run this, I get the following:
Error while waiting for Protractor to sync with the page: "angular could not be found on the window"
When I decide to use browser.ignoreSynchronization = true, both in the function, or in a beforeEach, with or without a following afterEach setting it to false, I get the following:
JavascriptError: angular is not defined
I can't seem to get any "useful" errors to help me debug it, and trying it in repl does not help, as I get the same issue.
To be comprehensive, trying my URL expect without getting the second window will give me the root, and the other will fail.
Just doing one or the other will cause the same problem.
Changing to regular syntax (element(by.css...)) does not change things.
So much for my first question...
It appears that my use of browser.getLocationAbsUrl() is meant to be used for an Angular page, and was causing my issue...
Essentially, even though I believed I was using pure Webdriver calls, that call still required Angular on the page to work...
As stated in another post, the use of browser.driver.getCurrentUrl() is a non-Angular call using Webdriver, and fixed the problem. Thus, the final code is the following...
browser.sleep(1000); //to wait for the page to load
browser.driver.getAllWindowHandles().then(function(handles) {
browser.driver.switchTo().window(handles[1]).then(function() {
expect(browser.driver.getCurrentUrl()).toContain('/console/login.jsp');
expect(browser.driver.findElement(By.css('th.login')).getText()).toEqual('Login');
});
});
This works without setting ignoreSynchronization, BTW.
I realized it would probably be something relatively simple to fix it, just didn't expect I'd get it that quickly (I intended on submitting the question last night, but posted it this morning instead).
In any case, I hope this will at least be a good reference for anyone else facing the same issue.
Seems like getLocationAbsUrl is angular abs url.
Try using the native driver getCurrentUrl instead.
-- expect(browser.getLocationAbsUrl()).toContain('/console/login.jsp');
++ expect(browser.driver.getCurrentUrl() ...

rootScope functions not being called when using ngIdle

I am using the ngIdle library and as the documentation states there are certain methods that you can call to check for user inactivity, and I have put these on the root scope.
app.run(function($rootScope) {
$rootScope.$on('IdleTimeout', function() {
alert('you will be logged out');
});
$rootScope.$on('IdleStart', function () {
alert('test');
});
});
These functions are never being called and I think that it might be a problem more to do with $rootscope rather than the ngidle library.
There are not any errors in console, and the ngidle library is included correctly. Any Ideas?
For me ng-idle works fine using the $rootScope. But I wasted some time waiting for the events to fire until I recognized, that the configuration expects seconds instead of milliseconds ;)
app.config(function(IdleProvider) {
// configure Idle settings
IdleProvider.idle(5); // in seconds!
IdleProvider.timeout(5); // in seconds!
});
I spent some time struggling with this too; none of the events were firing at all. Turns out that you need to call Idle.watch() so that the timing starts.
This isn't well documented; documentation is patchy and none of the examples I saw had this. All looked just like the code you have so I couldn't figure out what's wrong until I saw it in the Getting Started section on the library's GitHub page. It's not explicitly mentioned though, you have to look closely.
.run(function(Idle){
// start watching when the app runs. also starts the Keepalive service by default.
Idle.watch();
});
Then the second catch: once you get auto-logged out once, it will no longer time your session if you login again without reloading the app. You need to call Idle.watch() again from your Login method to reset the timers and start again.

Some of your tests did a full page reload - error when running Jasmine tests

I'm running into an issue where when I run my tests on Jasmine, I get this error below. The problem is, it seems to happen when I try to execute a certain amount of tests. It doesn't seem to be tied to a particular test, as if I comment out some, the tests pass. If I uncomment some tests, the error appears. If I comment out ones that were uncommented before, they all pass again. (ie if I have red, green, blue and orange test and it fails, I comment out orange and blue it passes, then I uncomment blue and orange it fails again, but if I comment out red and green it passes again).
Chrome 41.0.2272 (Mac OS X 10.10.1) ERROR Some of your tests did a
full page reload! Chrome 41.0.2272 (Mac OS X 10.10.1): Executed 16 of
29 (1 FAILED) ERROR (0.108 secs / 0.092 secs)
I'm stumped as to what is going on. The more tests I add, that's when this becomes an issue. Has anyone encountered this before? I have no idea what could be causing it, as nothing in any of my tests do any kind of redirection, and they all pass universally on another persons machine.
In my case the problem was that in my source code I had code directly setting the href on the location object, like window.location.href = 'somewhere';
In my specs I set up a onbeforeunload listener that just returns a string instead of allowing the redirect to take place:
beforeAll(() => {
window.onbeforeunload = () => 'Oh no!';
});
I suppose you are using window.location somewhere in your targeted code. In order to pass it just create a spy for the window.onbeforeunload
Example:
window.onbeforeunload = jasmine.createSpy();
Or even better use $window instead, and this will not happen.
Make sure that your tests are properly isolating all modules under test with mocks/spies. The behavior you are seeing says to me that your tests are not truly running in isolation - they are changing some state somewhere that will trigger a reload.
I recently encountered this error with Karma 0.13.12. I upgraded to Karma 0.13.14 and my tests work again. The problem for me (and probably also for #mqklin) was related to https://github.com/karma-runner/karma/issues/1656 and https://github.com/jasmine/jasmine/issues/945.
There are many ways this error can happen.
If your component has a form element, this might be the cause.
Whenever a button on the form is clicked, this error can happen, even tho your component contains no navigation logic.
What worked for me was upgrading Karma from 1.4.0 to 1.4.1 and changing the maximumSpecCallbackDepth in my jasmine.js file from 20 to 100.
creating a spy on the function which has the window.location / reload fixed the issue for me
Hope you have used window.location = "some url" in your code;
Faced similar problem, and solved by using the below changes.
Replaced window.location in the code with,
window.location.assign("some url");
Do the below in unit test:
spyOn(window.location, "assign").and.callFake(() => {
// Dummy assign call - so that your actual call will be faked and the reload will not happen.
});
You also need to make sure that modules are not being loaded twice. In my case, I had an AngularJS module file -e.g., auth.controller.js which contents were already bundled in a core.js file. Once I excluded the bundled files on karma, the error disappeared.
Try to reduce amount of describe sections or completely remove them. I don't know why, but it works for me.
I was using setTimeout(() => window.location.replace('/'), 10);
I used below code in my unit test and it worked for me.
spyOn(global, 'setTimeout');
In case it was ng-submit callback, which doesn't call "event.preventDefault()" and the browser reloads page. Mocking $location doesn't help in that situation.
According to angularjs documentation you should inject the $window module to be able to solve the testability issue you get. If you really want to do a full page refresh while routing, which will reload the whole application. But anyway...
So for example in component
.controller('ExampleController', ['$scope', '$window', function($scope, $window**)
{
$scope.doRerouteWithPageReload = function() {
return this.$window.location.href = "/myUrl";
};
And then in your test-file you import $window to the test-controller your way, then where you assign spies you can do something like this:
$window = { location: {href: jasmine.createSpy() };
And then the actual test is something like this:
expect($window.location.href).toBe("/myUrl");
Angularjs documentation for reading more about $window.
It will solve this Karma redirect error!
var html = '<script type="text/javascript">';
html += 'window.location = "' + urlToRedirect +'"';
html += '</script>';
$( '.wrapper' ).append( html );

Karma (AKA Testacular) rely on ng-app directive?

After spending a day and a half of code battles, i've realized that the e2e tests hanged because i've bootstraped manually and not using ng-app directive
first, FYI.
second, any idea why? How can it be fixed?
thanks
Lior
--
EDIT: here're two plunks that show it, using phone-cat tutorial example:
works in both browser and e2e:
http://plnkr.co/edit/AfLsug1LRi0euKf7TWJa
works interactively in browser, doesnt work in e2e runner:
http://plnkr.co/edit/20OeZ5eV2ZbzgS1qDYfr
Scenario runner appears to need to get a hold of ng-app (for the $injector). I adapted the fix identified here by Vojta Jína and it worked for me.
$(function() {
var myApp = $('#appId'); // Use whatever selector is appropriate here.
angular.bootstrap(myApp, [modules]); // modules is optional - see http://docs.angularjs.org/api/angular.bootstrap
myApp.addClass('ng-app'); // Adds the required ng-app
});
In addition, you may need to put a pause or wait in your beforeAll to allow enough time for manual bootstrapping to complete, e.g.,
beforeEach(function() {
browser().navigateTo('../../index.html');
pause();
});
This fix works but it's not that satisfactory imho. Is there any way to get rid of the pause/wait?

Categories

Resources