Skip to content

Commit

Permalink
Add tests for multi-statement evaluate_script via IIFE
Browse files Browse the repository at this point in the history
  • Loading branch information
twalpole committed May 30, 2019
1 parent acfda7d commit bdaed0b
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
14 changes: 12 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -611,13 +611,23 @@ In drivers which support it, you can easily execute JavaScript:
page.execute_script("$('body').empty()")
```

For simple expressions, you can return the result of the script. Note
that this may break with more complicated expressions:
For simple expressions, you can return the result of the script.

```ruby
result = page.evaluate_script('4 + 4');
```

For more complicated scripts you'll need to write them as one expression.

```ruby
result = page.evaluate_script(<<~JS, 3, element)
(function(n, el){
var val = parseInt(el.value, 10);
return n+val;
})(arguments[0], arguments[1])
JS
```

### <a name="modals"></a>Modals

In drivers which support it, you can accept, dismiss and respond to alerts, confirms and prompts.
Expand Down
12 changes: 12 additions & 0 deletions lib/capybara/spec/session/evaluate_script_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,16 @@
expect(el).to be_instance_of(Capybara::Node::Element)
expect(el).to eq(@session.find(:css, '#change'))
end

it 'should support multi statement via IIFE' do
@session.visit('/with_js')
@session.find(:css, '#change')
el = @session.evaluate_script(<<~JS)
(function(){
var el = document.getElementById('change');
return el;
})()
JS
expect(el).to eq(@session.find(:css, '#change'))
end
end
12 changes: 12 additions & 0 deletions lib/capybara/spec/session/node_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,18 @@
expect(el).to be_instance_of(Capybara::Node::Element)
expect(el).to eq(change)
end

it 'should support multiple statements via IIFE' do
@session.visit('/with_js')
change = @session.find(:css, '#change') # ensure page has loaded and element is available
res = change.evaluate_script(<<~JS, 3)
(function(n){
var el = this;
return [el, n];
}).apply(this, arguments)
JS
expect(res).to eq [change, 3]
end
end

describe '#evaluate_async_script', requires: %i[js es_args] do
Expand Down

0 comments on commit bdaed0b

Please sign in to comment.