Race condition with Capybara value set - ruby

I have faced an issue while using .set(#{value}) to fill the text field in registering form, e.g: the phone number i wanna put in is 506307 then it ended up with 063075.
The work-around i have been made is executing Javascript block like
execute_script("document.querySelector('#{selector}').value = '#{value}'")
However, using the same scripts applying for Webmobile based on React.JS, the scripts above just send the text but didn't send the onChange event, which cause another element cannot be selected/clicked -> made the test failed.
I came up with another approach is to use the send_keys #{value} to trigger the key-pressed event that would make browser think there was a key-pressed event happen for that form, but it ended up with race-condition like set(#{value}) as i mentioned.
The another work-around is using What is the best way to trigger onchange event in react js , but i tend to use the native Capybara actions before making that tricky Javascript.
So, is there any other way to interact / fill the form field which won't cause that Race condition issue ?
Thanks everybody in advance.

Note: Any "solution" suggested that is purely the use of execute_script to run some JS is a terrible idea since it completely bypasses the concept of testing what a user can do and can basically make your test worthless.
The root cause of the issue here is the JS behavior attached to the input not being able to handle the key events fast enough. The proper fix would be to fix the JS, however if that's not possible there's a few things you can try
First you can try changing the clear method being used by set
element.set('506307', clear: :backspace)
or
element.set('506307', clear: :none)
If that doesn't change anything then try clicking on the input, followed by a short sleep before setting the content
element.click
sleep 0.25
element.set('506307')
If none of those work around the issue we need to know exactly what JS behavior you have attached to the input and/or what events that JS behavior is listening to.

Related

Cypress Assertion that a button does not exist [duplicate]

I want to be able to click on a check box and test that an element is no longer in the DOM in Cypress. Can someone suggest how you do it?
// This is the Test when the checkbox is clicked and the element is there
cy.get('[type="checkbox"]').click();
cy.get('.check-box-sub-text').contains('Some text in this div.')
I want to do the opposite of the test above.
So when I click it again the div with the class check-box-sub-text should not be in the DOM.
Well this seems to work, so it tells me I have some more to learn about .should()
cy.get('.check-box-sub-text').should('not.exist');
You can also search for a text which is not supposed to exist:
cy.contains('test_invite_member#gmail.com').should('not.exist')
Here you have the result in Cypress: 0 matched elements
Reference: Docs - Assertions, Existence
Use .should('not.exist') to assert that an element does not exist in the DOM.
Do not use not.visible assertion. It would falsely pass in < 6.0, but properly fail now:
// for element that was removed from the DOM
// assertions below pass in < 6.0, but properly fail in 6.0+
.should('not.be.visible')
.should('not.contain', 'Text')
Migration Docs here: Migrating-to-Cypress-6-0
Cypress 6.x+ Migration
According to cypress docs on Existence
The very popular attempt which is a bit naive will work until it doesn't and then you'll have to rewrite it again... and again...
// retry until loading spinner no longer exists
cy.get('#loading').should('not.exist')
This doesn't really work for the title problem which is what most people will be looking for.
This works for the case that it is being removed. but in the case that you want it to never exist... It will retry until it goes away.
However, if you want to test that the element never exists in our case.
Yes lol. This is what you really want unless you want to just have your headache again another day.
// Goes through all the like elements, and says this object doesn't exist ever
cy.get(`img[src]`)
.then(($imageSection) => {
$imageSection.map((x, i) => { expect($imageSection[x].getAttribute('src')).to.not.equal(`${Cypress.config().baseUrl}/assets/images/imageName.jpg`) });
})
cy.get('[data-e2e="create-entity-field-relation-contact-name"]').should('not.exist');
might lead to some false results, as some error messages get hidden. It might be better to use
.should('not.visible');
in that case.
Here's what worked for me:
cy.get('[data-cy=parent]').should('not.have.descendants', 'img')
I check that some <div data-cy="parent"> has no images inside.
Regarding original question, you can set data-cy="something, i.e. child" attribute on inner nodes and use this assertion:
cy.get('[data-cy=parent]').should('not.have.descendants', '[data-cy=child]')
You can use get and contains together to differentiate HTML elements as well.
<button type='button'>Text 1</button>
<button type='button'>Text 2</button>
Let's say you have 2 buttons with different texts and you want to check if the first button doesn't exist then you can use;
cy.get('button').contains('Text 1').should('not.exist')
Could be done also using jQuery mode in cypress:
assert(Cypress.$('.check-box-sub-text').length==0)
I closed an element and checked should('not.exist') but the assertion failed as it existed in the DOM. It just that it is not visible anymore.
In such cases, should('not.visible') worked for me. I have just started using cypress. A lot to learn.
No try-catch flow in cypress
In java-selenium, we usually add the NoSuchElementException and do our cases. if UI is not displaying element for some Role based access cases.
You can also query for the matched elements inside the body or inside the element's parent container, and then do some assertions on its length:
cy.get("body").find(".check-box-sub-text").should("have.length", 0);
In case anyone comes across this, I was having the issue that neither .should('not.exist') nor .should('have.length', 0) worked - even worse: If the element I was querying was actually there right from the get-go, both asserts still returned true.
In my case this lead to the very strange situation that these three assertions, executed right after each other, were true, even though asserts 1+2 and 3 contradict each other:
cy.get('[data-cy="foobar"]').should('not.exist')
cy.get('[data-cy="foobar"]').should('have.length', 0)
cy.get('[data-cy="foobar"]').should('have.text', 'Foobar')
After extensive testing, I found out that this was simply a race condition problem. I was waiting on a backend call to finish before running the above 3 lines. Like so:
cy.wait('#someBackendCall')
cy.get('[data-cy="foobar"]').should('not.exist')
However once the backend called finished Cypress immediately ran the first two assertions and both were still true, because the DOM hadn't yet caught up rerendering based on the backend-data.
I added an explicit wait on an element that I knew was gonna be there in any case, so my code now looks something like this:
cy.wait('#someBackendCall')
cy.get('[data-cy="some-element"]').should('contain', 'I am always here after loading')
cy.get('[data-cy="foobar"]').should('not.exist')
You can also use below code
expect(opportunitynametext.include("Addon")).to.be.false
or
should('be.not.be.visible')
or
should('have.attr','minlength','2')
Voted element is correct but I highly recommend not to using anti-pattern saving you from a lot of headaches. Why? Yes, because;
Your application may use dynamic classes or ID's that change
Your selectors break from development changes to CSS styles or JS behavior
Luckily, it is possible to avoid both of these problems.
Don't target elements based on CSS attributes such as: id, class, tag
Don't target elements that may change their textContent
Add data-* attributes to make it easier to target elements
Example:
<button id="main" name="submission" role="button" data-cy="submit">Submit</button>
And if you want to be more specific and want to indentify more than one selector, it is always good to use .shouldchainer.
Example:
cy.get("ul").should(($li) => {
expect($li).to.be.visible
expect($li).to.contain("[data-cy=attribute-name]")
expect($li).to.not.contain("text or another selector")
})
If there is no element, we can use simple line like:
cy.get('[type="checkbox"]').should('not.exist')
In my case, Cypress was so fast, that simple .should('not.be.visible') was passing the test and after that, loader appears and test failed.
I've manage to success with this:
cy.get('.loader__wrapper')
.should('be.visible')
cy.get('.loader__wrapper', { timeout: 10000 })
.should('not.be.visible')
Also nice to set the timeout on 10 seconds when your application loads more than 4s.
I would use :
cy.get('.check-box-sub-text').should('not.be.visible');
This is safer than
cy.get('.check-box-sub-text').should('not.exist');
( The element can be present in the DOM but not visible with display: none or opacity: 0 )

how to delete alarm in lightning (in js)

I am banging my head looking at the code for ... quite some time.
I have a lightning event, created from ics (including an alarm).
I want to delete the alarm after something has occurred. I found calItemBase has mAlarms. But how to delete a single alarm? (there should be only one). What is the proper value of mAlarms if there is no alarm?
What to do with mAlarmLastAck and other properties?
My workaround is to recreate from ical without the alarm, but then the user looses categories and other things he set for the event in the UI.
Many thanks,
Klaus
A summary of the methods intended to be public for an item can be seen here: http://mxr.mozilla.org/comm-central/source/calendar/base/public/calIItemBase.idl
Specifically, there is a deleteAlarm method. Example:
var alarms = item.getAlarms({});
item.deleteAlarm(alarms[0]);
If you are sure you want to delete all alarms, you can also use the clearAlarms method.
item.clearAlarms();

How to set value of a hidden input with Selenium?

I've already looked at this but had no luck.
I've tried that example and it says undefined browserbot, I also tried the simple:
#browser.navigate.to "http://example.com"
#browser.execute_script("$('#hiddenthing').val('foo bar')")
which doesn't work at all, If i tried to set the value without javascript, it says you can't interact with hidden elements.
Any suggestions?
Selenium WebDriver cannot interact with hidden elements, it can only find them. If you attempt to do any user based interaction on a hidden element, you will get the error you saw above.
This is because SWD was created to emulate the things a user can directly do (with a few exceptions). Being able to interact with hidden elements falls outside the scope of SWD.
However, SWD does provide the ability to inject any javascript into the DOM of the browser (which makes handling these types of requirements more reasonable, if just a bit more difficult).
Try these two ways by executing javascript (as you saw from the above thread you linked to). Just remember that it requires the use of the return command:
#browser.execute_script("return document.getElementById('hiddinthing').value = 'foo';")
or if you do have jQuery
#browser.execute_script("return $('#hiddenthing').val('foo');")

Acting on an element in onRender doesn't work

When I try to act on some HTML elements in the onRender method (or in a item:rendered callback), it fails.
Example:
Bars.EditGallery = Backbone.Marionette.ItemView.extend
template: 'bars/edit_gallery'
className: 'edit-gallery'
onRender: ->
# If I just write #$('select').chosen(), it doesn't work
# despite the jQuery object contains what I expect.
# To get it working, I have to write:
callback = -> #$('select').chosen()
setTimeout(callback, 0)
It's the same with others actions, like giving the focus to a field.
How do you deal with that? The trick with setTimeout works but it is not very elegant.
I've seen this happen when the templates used for rendering are loaded asynchronously. I thought I a pull request had fixed this in a recent release. What version of Marionette are you using?
But it looks like you're using JST, anyways, so that shouldn't be the problem. Is there anything else in your setup that is causing the render to happen asynchronously?
It seems likely that there is some asynchronous issue happening, though. Since using setTimeout fixes the problem, that makes me think the rendering is not completing before the onRender method is called.
Also - it can be hard tell if the jQuery selector is actually returning the object you want, right away. If you're using console.log to check the selector, this may be giving false results. console.log is itself asynchronous (in most browsers, anyways... not sure about all) which means the request to log the item gets queued up at the end of the event loop. It's likely that the DOM element is available by the time the logging happens.
FWIW: I use onRender for this exact purpose on a regular basis, and I've never had to use setTimeout to make it work. So my assumption is something funny going on with the rendering process, related to async stuff.
This problem is caused by Chosen, as mentioned in this issue.

Get list of currently dispatched events

I know this question may seem weird but I'd like to get a list of currently dispatched events.
The thing is that I am a lazy man and I would like to check if the 'checkout_cart_add_product_complete' has been fired without creating an observer for it.
So the idea is to get an array of all dispatched events and do an in_array on it :)
I thought that Mage::getEvents()->getAllEvents() would throw some info but it just returns an empty array.
I also digged a bit in lib/Varien/Event files and folders but didn't manage to be successful at creating an observer programmatically. Yep, I know, why being simple while one can be complicated ? :)
So this main question (getting a list of dispatched events) hides another (for the pure knowledge) wich would be "how to create an observer programmatically".
What do you think?
Thanks a lot!
Take a look at dispatchEvent and you'll see that events are only loaded from the assorted config.xml files, via SimpleXML. I cannot see any way to intercept this except to override Mage_Core_Model_App.
Of course there cannot be an event-dispatched-event, that would create an infinite loop, so there is no way to observe all events.
If you need to see events for development my advice would be to set a breakpoint in dispatchEvent with your debugger, that way you get to see not only the event names but also the objects passed as parameters too. I've tried other ways before but this was most convenient for me.
I need to do the same and I think it's possible to trick magento by the function getEventConfig in Mage_Core_Model_Config. You could force him to add automatically a default observer.

Resources