1 | ##
|
---|
2 | # Wait until the test condition is true or a timeout occurs. Useful for waiting
|
---|
3 | # on a server response or for a ui change (fadeIn, etc.) to occur.
|
---|
4 | #
|
---|
5 | # @param testFx javascript condition that evaluates to a boolean,
|
---|
6 | # it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
|
---|
7 | # as a callback function.
|
---|
8 | # @param onReady what to do when testFx condition is fulfilled,
|
---|
9 | # it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
|
---|
10 | # as a callback function.
|
---|
11 | # @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
|
---|
12 | ##
|
---|
13 | waitFor = (testFx, onReady, timeOutMillis=3000) ->
|
---|
14 | start = new Date().getTime()
|
---|
15 | condition = false
|
---|
16 | f = ->
|
---|
17 | if (new Date().getTime() - start < timeOutMillis) and not condition
|
---|
18 | # If not time-out yet and condition not yet fulfilled
|
---|
19 | condition = (if typeof testFx is 'string' then eval testFx else testFx()) #< defensive code
|
---|
20 | else
|
---|
21 | if not condition
|
---|
22 | # If condition still not fulfilled (timeout but condition is 'false')
|
---|
23 | console.log "'waitFor()' timeout"
|
---|
24 | phantom.exit 1
|
---|
25 | else
|
---|
26 | # Condition fulfilled (timeout and/or condition is 'true')
|
---|
27 | console.log "'waitFor()' finished in #{new Date().getTime() - start}ms."
|
---|
28 | if typeof onReady is 'string' then eval onReady else onReady() #< Do what it's supposed to do once the condition is fulfilled
|
---|
29 | clearInterval interval #< Stop this interval
|
---|
30 | interval = setInterval f, 250 #< repeat check every 250ms
|
---|
31 |
|
---|
32 |
|
---|
33 | page = require('webpage').create()
|
---|
34 |
|
---|
35 | # Open Twitter on 'sencha' profile and, onPageLoad, do...
|
---|
36 | page.open 'http://twitter.com/#!/sencha', (status) ->
|
---|
37 | # Check for page load success
|
---|
38 | if status isnt 'success'
|
---|
39 | console.log 'Unable to access network'
|
---|
40 | else
|
---|
41 | # Wait for 'signin-dropdown' to be visible
|
---|
42 | waitFor ->
|
---|
43 | # Check in the page if a specific element is now visible
|
---|
44 | page.evaluate ->
|
---|
45 | $('#signin-dropdown').is ':visible'
|
---|
46 | , ->
|
---|
47 | console.log 'The sign-in dialog should be visible now.'
|
---|
48 | phantom.exit()
|
---|