2

I am trying to get current url and want to store it as string but .then is always return undefined. Following is the function code:

navigateToLandingPage() {
          let EC = protractor.ExpectedConditions;
          let currentURL: string;
          browser.getCurrentUrl().then ( (url) => {
            currentURL = url;
          } );
          if (currentURL !== 'operator') {
           browser.get('localhost:3000/#/operator');
           browser.wait(EC.urlContains('/operator'), 10000);
      }

I am calling it form spec in this way:

describe('Checking Module', () => {
  let page: CalendarModule;
  let EC = protractor.ExpectedConditions;
  beforeEach(() => {
    page = new CalendarModule();
  });
  it('Clicking on Calendar should redirect to Calendar Module', () => {
      page.commonMethodObj.navigateToLandingPage();
      let calendarLink = page.getCalendarLink();
       calendarLink.click().then(() => {
       browser.wait(EC.urlContains('/calendar'), 50000);
       expect(browser.getCurrentUrl()).toMatch('/calendar');
      });
  });
});

I am using following versions of dependencies:

"@angular/core": "2.3.1",
"jasmine-core": "2.5.2",
"jasmine-spec-reporter": "2.5.0",
"protractor": "~4.0.13"
DanzerZoneJS
  • 441
  • 3
  • 7
  • 23
  • `calendarLink.click()` method is thenable; however, it is not needed since Protractor makes these asynchronous calls appear syncrhonous with jasminewd. – cnishina Jan 13 '17 at 18:57

1 Answers1

4

The entire behavior and the flow of the code execution is asynchronous and orchestrated by the WebDriver Control Flow. In other words, you cannot expect that currentURL variable would actually get the current URL value on this line:

if (currentURL !== 'operator') {

Instead, work inside the callback:

browser.getCurrentUrl().then ( (currentURL) => {  
    if (currentURL !== 'operator') {
        browser.get('localhost:3000/#/operator');
        browser.wait(EC.urlContains('/operator'), 10000);
    }
});
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Yeah correct!! But what if i want to return something from promise and use it later. How could it be achieved then?? – DanzerZoneJS Jan 16 '17 at 04:37
  • @ArjunSingh awesome, you can use the deferred object ([example](http://stackoverflow.com/a/24290262/771848)). – alecxe Jan 16 '17 at 12:45