You could simply create a method on your page object class named initialize_page
. This method will be called immediately after the page loads. In that method you can make the call to execute_script
(a method on the page) passing the javascript you wish to execute.
Is monkey patching PageObject::PageFactory#visit_page a good idea?
-
06-03-2022 - |
Question
A developer recently asked if our tests could execute some javascript every time a page is opened. See bug 44299 for more details.
Executing javascript is trivial:
browser.execute_script('return mw.loader.getModuleNames().filter(function (module) { return mw.loader.getState(module) === "error"; }).length === 0;')
#=> true
We are using page-object's #visit_page
to open pages. An easy way to make sure the javascript in the above example is executed every time a page is opened would be to monkey patch the #visit_page
method.
alias_method
chain (from question 4470108) looks like a simple way to do it.
Is there a better way?
Solution
OTHER TIPS
It seems to me like you are doing a bit too much work for something very simple. I'm not sure what framework you are using, but do you have an application wide JavaScript file? For a rails application I would write a test.js.erb:
<%= %q+browser.execute_script('return mw.loader.getModuleNames().filter(function (module) { return mw.loader.getState(module) === "error"; }).length === 0;')+ if Rails.env.test? %>
and add //= test
to your application manifest