protractor icon indicating copy to clipboard operation
protractor copied to clipboard

Error while waiting for Protractor to sync with the page: true

Open rolandjitsu opened this issue 9 years ago • 23 comments

Bug report

  • Node Version: 7.4.0
  • Protractor Version: 5.1.2
  • Angular Version: 4.2.2
  • Browser(s): Chrome
  • Operating System and Version macOS 10.12
  • Your protractor configuration file
// Protractor configuration file,
// see link for more information https://github.com/angular/protractor/blob/master/lib/config.ts
const {SpecReporter} = require('jasmine-spec-reporter');


exports.config = {
	allScriptsTimeout: 120000,
	specs: [
		'./e2e/**/*.e2e-spec.ts'
	],
	capabilities: {
		browserName: 'chrome',
		chromeOptions: {
			'args': ['--js-flags=--expose-gc'],
			'perfLoggingPrefs': {
				'traceCategories': 'v8,blink.console,disabled-by-default-devtools.timeline,devtools.timeline'
			}
		},
		loggingPrefs: {
			performance: 'ALL',
			browser: 'ALL'
		}
	},
	directConnect: true,
	baseUrl: 'http://localhost:4224/',
	framework: 'jasmine',
	jasmineNodeOpts: {
		showColors: true,
		showTiming: true,
		defaultTimeoutInterval: 120000,
		print: () => {}
	},
	// Option for Angular to test against Angular 2+ applications on the page.
	// Protractor will wait for the app to be stable before each action, and search within all apps when finding elements.
	rootElement: 'infarm-app',
	onPrepare: () => {
		// Add jasmine spec reporter
		jasmine.getEnv()
			.addReporter(new SpecReporter({spec: {displayStacktrace: true}}));
		// Include jasmine expect
		require('jasmine-expect');
		// Transpile all TS to JS
		require('ts-node')
			.register({
				project: 'e2e/tsconfig.e2e.json'
			});
	}
};
  • A relevant example test
// home.po.ts
import {browser} from 'protractor';

export class HomePage {
	navigateTo(): any {
		return browser.get('/');
	}
}
// login.po.ts
import {browser, by, element} from 'protractor';


export class LoginPage {
	username = element(by.css('input[name="username"]'));
	password = element(by.css('input[name="password"]'));
	submit = element(by.buttonText('Login'));

	login(username: string, password: string): void {
		this.username.sendKeys(username);
		this.password.sendKeys(password);
		this.submit.click();
	}

	navigateTo(): any {
		return browser.get('/#/login');
	}
}
import {browser} from 'protractor';
import {HomePage} from './home.po';
import {LoginPage} from './login.po';


// https://github.com/angular/protractor/blob/master/docs/timeouts.md#how-to-disable-waiting-for-angular
describe('Dashboard', () => {
	beforeEach(() => {
		const homePage = new HomePage();
		homePage.navigateTo();
	});

	describe('Authentication', () => {
		it('should redirect to /login when trying to access the dashboard without being authenticated', () => {
			// const homePage = new HomePage();
			// await homePage.navigateTo();
			const url = browser.getCurrentUrl();
			expect(url)
				.toEndWith('/#/login');
		});

		it('should fail to login if not provided the proper credentials', () => {
			const loginPage = new LoginPage();
			loginPage.login('[email protected]', 'test');
			const url = browser.getCurrentUrl();
			expect(url)
				.toEndWith('/#/login');
		});

		it('should login if provided the proper credentials', () => {
			// browser.ignoreSynchronization = true;

			const loginPage = new LoginPage();
			loginPage.login('[email protected]', 'ActualPass');

			// await browser.sleep(10000);

			const url = browser.getCurrentUrl();


			expect(url)
				.toEndWith('/#/');
		});
	});
});
  • Output from running the test
Spec started

  Dashboard

    Authentication
      ✓ should redirect to /login when trying to access the dashboard without being authenticated
      ✗ should fail to login if not provided the proper credentials
        - Failed: Error while waiting for Protractor to sync with the page: true
            at runWaitForAngularScript.then (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/protractor/lib/browser.ts:653:19)
            at ManagedPromise.invokeCallback_ (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:13
66:14)
            at TaskQueue.execute_ (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2970:14)
            at TaskQueue.executeNext_ (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2953:27)
            at asyncRun (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2813:27)
            at /Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:676:7
            at process._tickCallback (internal/process/next_tick.js:103:7)
        From: Task: Run it("should fail to login if not provided the proper credentials") in control flow
            at Object.<anonymous> (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/jasminewd2/index.js:94:19)
            at /Users/rolandjitsu/Projects/infarm/dashboard/node_modules/jasminewd2/index.js:64:48
            at ControlFlow.emit (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/events.js:62:21)
            at ControlFlow.shutdown_ (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2565:10)
            at shutdownTask_.MicroTask (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2490:53)
            at MicroTask.asyncRun (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2619:9)
            at /Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:676:7
            at process._tickCallback (internal/process/next_tick.js:103:7)
        From asynchronous test:
        Error
            at Suite.<anonymous> (/Users/rolandjitsu/Projects/infarm/dashboard/e2e/app.e2e-spec.ts:22:3)
            at Suite.<anonymous> (/Users/rolandjitsu/Projects/infarm/dashboard/e2e/app.e2e-spec.ts:13:2)
            at Object.<anonymous> (/Users/rolandjitsu/Projects/infarm/dashboard/e2e/app.e2e-spec.ts:7:1)
            at Module._compile (module.js:571:32)
            at Module.m._compile (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/ts-node/src/index.ts:382:23)
            at Module._extensions..js (module.js:580:10)
            at Object.require.extensions.(anonymous function) [as .ts] (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/ts-node/src
/index.ts:385:12)
            at Module.load (module.js:488:32)
            at tryModuleLoad (module.js:447:12)
      ✗ should login if provided the proper credentials
        - Failed: Error while waiting for Protractor to sync with the page: true
            at runWaitForAngularScript.then (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/protractor/lib/browser.ts:653:19)
            at ManagedPromise.invokeCallback_ (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:13
66:14)
            at TaskQueue.execute_ (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2970:14)
            at TaskQueue.executeNext_ (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2953:27)
            at asyncRun (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2813:27)
            at /Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:676:7
            at process._tickCallback (internal/process/next_tick.js:103:7)
        From: Task: Run it("should login if provided the proper credentials") in control flow
            at Object.<anonymous> (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/jasminewd2/index.js:94:19)
            at /Users/rolandjitsu/Projects/infarm/dashboard/node_modules/jasminewd2/index.js:64:48
            at ControlFlow.emit (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/events.js:62:21)
            at ControlFlow.shutdown_ (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2565:10)
           at shutdownTask_.MicroTask (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2490:53)
            at MicroTask.asyncRun (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:2619:9)
            at /Users/rolandjitsu/Projects/infarm/dashboard/node_modules/selenium-webdriver/lib/promise.js:676:7
            at process._tickCallback (internal/process/next_tick.js:103:7)
        From asynchronous test:
        Error
            at Suite.<anonymous> (/Users/rolandjitsu/Projects/infarm/dashboard/e2e/app.e2e-spec.ts:30:3)
            at Suite.<anonymous> (/Users/rolandjitsu/Projects/infarm/dashboard/e2e/app.e2e-spec.ts:13:2)
            at Object.<anonymous> (/Users/rolandjitsu/Projects/infarm/dashboard/e2e/app.e2e-spec.ts:7:1)
            at Module._compile (module.js:571:32)
            at Module.m._compile (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/ts-node/src/index.ts:382:23)
            at Module._extensions..js (module.js:580:10)
            at Object.require.extensions.(anonymous function) [as .ts] (/Users/rolandjitsu/Projects/infarm/dashboard/node_modules/ts-node/src
/index.ts:385:12)
            at Module.load (module.js:488:32)
            at tryModuleLoad (module.js:447:12)
  • Steps to reproduce the bug I'm using Angular CLI ng test to run the tests. When the user lands on the page they get redirected to #/login if not authenticated, then if they fill wrong credentials they stay on the same page, otherwise they get redirected to /#/. I tried to use browser.ignoreSynchronization = true; and browser.sleep() on the last test, which looks like it worked, but the second test still failed. Also note that the interactions with the browser actually work, but the tests fail anyway.
  • The URL you are running your tests against (if relevant)

rolandjitsu avatar Jun 17 '17 09:06 rolandjitsu

I also tried to disable flow control:

// Protractor configuration file,
// see link for more information https://github.com/angular/protractor/blob/master/lib/config.ts
const {SpecReporter} = require('jasmine-spec-reporter');


exports.config = {
	allScriptsTimeout: 120000,
	specs: [
		'./e2e/**/*.e2e-spec.ts'
	],
	capabilities: {
		browserName: 'chrome',
		chromeOptions: {
			// Use headless Chrome https://github.com/angular/protractor/blob/master/docs/browser-setup.md#using-headless-chrome
			'args': ['--headless', '--js-flags=--expose-gc'],
			'perfLoggingPrefs': {
				'traceCategories': 'v8,blink.console,disabled-by-default-devtools.timeline,devtools.timeline'
			}
		},
		loggingPrefs: {
			performance: 'ALL',
			browser: 'ALL'
		}
	},
	directConnect: true,
	baseUrl: 'http://localhost:4224/',
	framework: 'jasmine',
	jasmineNodeOpts: {
		showColors: true,
		showTiming: true,
		defaultTimeoutInterval: 120000,
		print: () => {}
	},
	// Option for Angular to test against Angular 2+ applications on the page.
	// Protractor will wait for the app to be stable before each action, and search within all apps when finding elements.
	rootElement: 'infarm-app',
	// Turn off control flow (https://github.com/angular/protractor/tree/master/exampleTypescript/asyncAwait)
	SELENIUM_PROMISE_MANAGER: false,
	onPrepare: () => {
		// Add jasmine spec reporter
		jasmine.getEnv()
			.addReporter(new SpecReporter({spec: {displayStacktrace: true}}));
		// Include jasmine expect
		require('jasmine-expect');
		// Transpile all TS to JS
		require('ts-node')
			.register({
				project: 'e2e/tsconfig.e2e.json'
			});
	}
};

With tests:

import {HomePage} from './home.po';
import {LoginPage} from './login.po';
import {getCurrentUrl} from './utils';


describe('Dashboard', () => {
	describe('Authentication', () => {
		it('should redirect to /login when trying to access the dashboard without being authenticated', async function () {
			const homePage = new HomePage();
			await homePage.navigateTo();
			const url = await getCurrentUrl();
			expect(url).toEndWith('/#/login');
		});

		it('should fail to login if not provided the proper credentials', async function () {
			const loginPage = new LoginPage();

			await loginPage.navigateTo();
			await loginPage.login('[email protected]', 'test');

			const url = await getCurrentUrl();
			expect(url).toEndWith('/#/login');
		});

		it('should login if provided the proper credentials', async function () {
			const loginPage = new LoginPage();

			await loginPage.navigateTo();
			await loginPage.login('[email protected]', 'ActualPassword');

			const url = await getCurrentUrl();
			expect(url).toEndWith('/#/');
		});

		it('should redirect to home page if already authenticated', async function () {
			const loginPage = new LoginPage();

			await loginPage.navigateTo();
			await loginPage.login('[email protected]', 'ActualPassword');

			const before = await getCurrentUrl();
			expect(before).toEndWith('/#/');

			await loginPage.navigateTo();

			const after = await getCurrentUrl();
			expect(after).toEndWith('/#/');
		});
	});
});
// login.po.ts
import {browser, by, element} from 'protractor';


export class LoginPage {
	get username() {
		return element(by.css('input[name="username"]'));
	}
	get password() {
		return element(by.css('input[name="password"]'));
	}
	get submit() {
		return element(by.buttonText('Login'));
	}

	async login(username: string, password: string): Promise<void> {
		await Promise.all([this.username.sendKeys(username), this.password.sendKeys(password)]);
		await this.submit.click();
	}

	async navigateTo(): Promise<void> {
		await browser.get('/#/login');
	}
}
// home.po.ts
import {browser} from 'protractor';

export class HomePage {
	async navigateTo(): Promise<void> {
		await browser.get('/');
	}
}
// utils.ts
import {browser} from 'protractor';

export async function getCurrentUrl(): Promise<string> {
	const url = await browser.getCurrentUrl();
	return url;
}

rolandjitsu avatar Jun 17 '17 11:06 rolandjitsu

I have a similar setup (login page that redirects to to another route in the Angular 4 app), that exhibits the same issue consistently when run inside of docker with chrome. Works on mac mostly but has intermittent failures. The error I get is:

Error: Error while waiting for Protractor to sync with the page: "window.angular is undefined. This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping. See http://git.io/v4gXM for details"

Which is incorrect since both my login page and the post login page are routes within the same angular 4 application. My tests are using async/await with selenium promise manager disabled.

This makes protractor basically unusable for my app, since all the functionality lies behind the login page.

viewstack avatar Jul 09 '17 01:07 viewstack

@rolandjitsu and @viewstack ,

Can you also provide an example project on git so we can check this? Tnx in advance

wswebcreation avatar Jul 09 '17 09:07 wswebcreation

@wswebcreation . Update on this. I had an external call to a pubnub service on login. This seemed to be the issue. Running that in ngZone.runOutsideAngular() seems to have resolved it. I'll try running some more in my CI environment and report back if its not fixed.

viewstack avatar Jul 09 '17 15:07 viewstack

@wswebcreation unfortunately the codebase is under IP and I cannot share.

rolandjitsu avatar Jul 09 '17 16:07 rolandjitsu

@rolandjitsu , it's hard to debug without an example. Do you happen to know a example project on the web that can be compared to the project you are working on?

wswebcreation avatar Jul 09 '17 18:07 wswebcreation

@wswebcreation I agree, but there's nothing I can do about it 😞 I'm not sure there is.

I've also made sure there's no long running task that would force protractor to wait for too long, so that's why I don't understand why it waits.

And why is the error message Error while waiting for Protractor to sync with the page: true, if it's true should it not be fine?

rolandjitsu avatar Jul 10 '17 10:07 rolandjitsu

We are also getting similar issue since last week. our test cases were working fine since last year.

After login into the app, all the test cases are failing. we have developed e2e test case for native angular app for chrome browser only.

Note: In App we are using $interval as suggested to mitigate the problem while working on e2e protractor test cases.

Failed: Timed out waiting for Protractor to synchronize with the page after 600 seconds. Please see https://github.com/angular/protractor/blob/master/docs/faq.md While waiting for element with locator - Locator: By(css selector, a). The following tasks were pending: - $http: http://XXXX. 

Conf file-

var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
var log4js = require('log4js');
var params = process.argv;
var args = process.argv.slice(3);

exports.config = {
  //seleniumServerJar: './node_modules/gulp-protractor/node_modules/protractor/selenium/selenium-server-standalone-2.48.2.jar',
  seleniumAddress: 'http://localhost:4444/wd/hub',
  allScriptsTimeout: 10*60*1000,
  framework: 'jasmine2',

  onPrepare: function () {
    var appHandle = "";
    var recursionDepth= 0, maxDepth = 100; // edit as necessary.
    function getAppWindow(){
      browser.driver.getAllWindowHandles().then(function(handles){
        if(handles.length == 1){
          recursionDepth += 1;
          if (recursionDepth == maxDepth){
            return false;
          }
          getAppWindow();
        }//end if
        if(handles.length == 2){
          browser.driver.switchTo().window(handles[1]);
          browser.driver.getWindowHandle().then(function(currentHandle){
            appHandle = currentHandle;
          });
        }
      });//end function(handles)
    }//end function getAppWindow()

    beforeEach(function() {  //THIS MAY NOT BE NECESSARY BEFORE EVERY SCENARIO
      getAppWindow();
    });

    browser.manage().timeouts().implicitlyWait(10000);
 
    //browser.ignoreSynchronization = true

    jasmine.getEnv().addReporter(
      new Jasmine2HtmlReporter({
        savePath: __dirname+'/qualityreports/e2e',
        takeScreenshots: false,
        filePrefix: 'automationReport',
        consolidate: true,
        cleanDestination: false,
        consolidateAll: true

      })
    );
  },

  suites:{
    suiteone:['./test/e2e/folder1/**/*Spec.js',
      './test/e2e/folder2/**/*Spec.js',
      './test/e2e/folder3/**/*Spec.js']
  },

  capabilities: {
    'browserName': 'chrome',
    'chromeOptions': {
      'args': ['load-and-launch-app='+ 'D:/latest/code']
    }
  },

  appenders: [
    {
      "type": "file",
      "filename": "./e2eTestLogs/logfile.log",
      "maxLogSize": 20480,
      "backups": 3,
      "category": "relative-logger"
    }
  ],

  params: {
    Login: {
      username: 'abc',
      password: 'xyz'
   }
  },

  // Options to be passed to Jasmine-node.
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 40*60*1000
  }
};

Can someone please help here.

tyaga001 avatar Jul 11 '17 06:07 tyaga001

@heathkit , can you also check this one. I can't find the issue and we don't have a example project which makes it harder to debug

wswebcreation avatar Jul 11 '17 08:07 wswebcreation

@heathkit @wswebcreation - Could you please help here.

tyaga001 avatar Jul 13 '17 05:07 tyaga001

@tyaga001 , did you also look a this and this?

wswebcreation avatar Jul 13 '17 06:07 wswebcreation

@wswebcreation - But ng-zone concept come for angular2. since last year all our test cases were running fine. Since last two weeks problem occurs after login in the App.

Angular version- 1.3 Protractor version - 5.1.2 node version - 6.10.2

Do ng-zone need to use in e2e test or Dev team need to use this to handle external APIs. Please suggest.

tyaga001 avatar Jul 17 '17 04:07 tyaga001

Hi @tyaga001 ,

No, you don't need it. What I find remarkable in your post is that you are saying that since last year all our test cases were running fine. Since last two weeks problem occurs after login in the App.

Can you explain what has changed in your:

  • application (I assume the application has been developed / changed since last year)
  • test setup. Did the version of protractor or other dependencies were upgraded?

If nothing has changed it should still be working, so 1 of the above 2 broke it.

wswebcreation avatar Jul 17 '17 04:07 wswebcreation

@wswebcreation - Thanks for your prompt reply. it really means a lot.

we introduce $timeout in App code & that is creating the problem so we use $interval now & problem resolved. Thanks for the help.

tyaga001 avatar Jul 24 '17 12:07 tyaga001

@tyaga001

Great that it is solved for you and thanks for the feedback

wswebcreation avatar Jul 24 '17 17:07 wswebcreation

I have the same issue and after investigating, I think I found the bug : if you configure Protractor with useAllAngular2AppRoots: true, there is no issue. But If you use rootElement: 'my-app' instead the bug appears.

By looking at the code, it seems that when using rootElement the callback here is called with true which is then interpreted as an error here. If useAllAngular2AppRoots is used, the callback is called here with no parameter hence no error.

Groggy avatar Aug 02 '17 16:08 Groggy

@Groggy spot on! Using that config seems to work indeed. I've also noticed that it happens when I try to get the browser url after a redirect happened in the app:

it('should ...', async () => {
    const url = await getCurrentUrl(); // removing this will allow tests to run properly
    console.log(url)
});

async function getCurrentUrl(): Promise<string> {
    const url = await browser.getCurrentUrl();
    return url;
}

rolandjitsu avatar Aug 16 '17 08:08 rolandjitsu

@rolandjitsu

Is this fixed for you now?

wswebcreation avatar Aug 16 '17 19:08 wswebcreation

@wswebcreation I wouldn't say that.

The behaviour of rootElement: 'my-app' and useAllAngular2AppRoots: true should be the same in this instance, meaning the error we see shouldn't occur just with one, but not the other.

rolandjitsu avatar Aug 17 '17 07:08 rolandjitsu

@rolandjitsu - I raised a separate issue #4543 as I didn't see yours at first.

The problem is at clientsidescripts.js#L181 because testability.whenStable(callback) sometimes passes true to the callback method, which is then interpreted as an error.

If your Angular code under test doesn't have any pending tasks, then the zone is considered stable and testability.whenStable(callback) passes false to the callback method immediately. This works fine.

But if there are any pending tasks - http.get or setTimeout or similar - then the zone is considered unstable; testability.whenStable(callback) passes true to the callback method once the zone becomes stable.

I issued pull request #4544 to fix this.

@viewstack - Your problem is different, my PR won't fix that.

andrewpmontgomery avatar Oct 18 '17 13:10 andrewpmontgomery