Selenium-Webdriver w/ Chai as Promised and Mocha f

2019-09-21 00:20发布

I've got a simple coffeescript test w/ Selenium-Webdriver using Chai-as-Promised and Mocha which is supposed to test a web page that I have that uses an AJAX call to do authentication once a login button is pressed:

selenium = require 'selenium-webdriver'
chai = require 'chai'
chai.use require 'chai-as-promised'
expect = chai.expect

before ->
  @timeout 10000
  @driver = new selenium.Builder()
    .withCapabilities(selenium.Capabilities.chrome())
    .build()
  @driver.getWindowHandle()

after ->
  @driver.quit()

describe 'Test Login', ->
  beforeEach ->
    @driver.get 'http://DOMAIN/login/'

  it 'submitting login', ->
    @driver.findElement(id: 'email').sendKeys('foo@bar.com')  
    @driver.findElement(id: 'password').sendKeys('foo')
    @driver.findElement(css: '#login-btn').submit()
    expect(@driver.findElement(id: '#login-profile')).to.eventually.be.true
    expect(@driver.getCurrentUrl()).to.eventually.equal 'http://DOMAIN/profile/'

The way the login page works is that once you click login an AJAX call is made, and if login is successful the page is redirected via document.location.href to /profile/.

However, when this script runs the browser opens and goes to the login page, it's filled out correctly, but then as soon as it's clicked it fails.

I think what's happening is the browser is not waiting for the result of the AJAX call and subsequent redirect, but I though the whole idea of promises would be that eventually would wait until some timeout period to verify that #login-profile would need to show up.

Do I need to add that explicitly? If so, how?

1条回答
Explosion°爆炸
2楼-- · 2019-09-21 01:14

I was able to get this to work using the wait syntax:

@driver.wait(-> driver.isElementPresent selenium.By.id("login-profile"), 10000)

thanks to this post.

The full test:

it 'submitting login', ->
    driver = @driver
    @driver.findElement(id: 'email').sendKeys('foo@bar.com')  
    @driver.findElement(id: 'password').sendKeys('foo')
    @driver.findElement(css: '#login-btn').submit()
    @driver.wait(-> driver.isElementPresent selenium.By.id("login-profile"), 10000)
    expect(@driver.getCurrentUrl()).to.eventually.equal 'http://DOMAIN/profile/'
查看更多
登录 后发表回答