Testing a non-trivial AngularJS app with Karma

Issue

I’ve been writing attempting to setup a testing suite for an application that I’ve been developing. The app is hosted locally, and on most accounts works fine. I’ve tried to setup karma via the instructions on AngularJS’s site, and on Karma’s site, and pretty much every other site I could find, but I keep getting the same error.

Here’s my conf:

urlRoot = '/karma/';
frameworks = ['ng-scenario'];
files = [
  ANGULAR_SCENARIO,
  ANGULAR_SCENARIO_ADAPTER,
  'spec/e2e/*.spec.js'
];
browsers = [
  'Firefox',
];
proxies = {
  '/': 'http://localhost/web/',
};
port = 9876;
singleRun = false;
junitReporter = {
  outputFile: 'logs/e2e.xml',
};
logLevel = LOG_DEBUG;

And an example spec:

describe('login test', function() {

  it('should login', function(){
    browser().navigateTo('/');
    if(browser().window().path() != '/'){
      expect(element('[ng-model="username"]').count()).toBeGreaterThan(0);
      input('username').enter('username');
      input('password').enter('password');
      element('#submit').click();
      sleep(3);
    }
    expect(browser().window().path()).toEqual('/');
  });

  it('should logout', function(){
    element('#quit').click();
    element('quit_dialog').click();
    sleep(1);
  });
});

When I run the test in an html file via angular-scenario it works fine, all green. When I run it via karma I get the following errors:

Error: Permission denied to access property 'angular'

I suspect that it’s a Cross-Domain issue, but why? And if so, how can I fix it?

NOTE: My application redirects someone to the login page from the base url. I assumed karma could handle a redirection.

EDIT: I cloned angular-seed and ran it untouched (apart from changing the proxy url), and that went fine.

Solution

When there is a full page reload, Karma loses the “hook.”

The best solution that I currently employ is to manually navigate to the page.

For example, if you start out on “/login” and log in, which causes the page to redirect to “/home”, Karma will lose the hook. So after you log in, you need to re-gain the hook by manually loading the page, eg:

browser().navigate("/login");
//Do login
element("submitButton").click();
//Page gets redirected to /home after successful login, Karma loses hook
browser().navigate("/home"); //Manually navigate to page to regain hook

It’s a bit of a hack, but its the best way I know.

Answered By – Eric Zhang

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.