How do I grab an id of an element as a text variable and reuse it later in Cypress - automation

<li class="MuiButtonBase-root
MuiMenuItem-root Menu-module_menuItem__2_dUv
MuiMenuItem-gutters
MuiMenuItem-root
Menu-module_menuItem__2_dUv
MuiMenuItem-gutters css-564zr3"
tabindex="-1"
role="menuitem"
id="hello.world">
hello.world
<span class="MuiTouchRipple-root css-w0pj6f"></span>
</li>
Here I want to store the value of id which is "hello.world" as a string and use it for comparison later
const text=cy.get('span>li').eq(0).invoke('text').as('text');
cy.get('body').contains(text);

Have you actually looked an any Cypress examples? None of then show you that test code.
Try it this way instead
cy.get('li').eq(0).invoke('text').then(text => {
cy.get('body').contains(text)
})

In Cypress, commands do not return their subjects, instead yield them so, your code is not going to work. Refer Cypress command- .then() [https://docs.cypress.io/api/commands/then] You can do something like:
cy.get('span>li').first().then(($textVal) => {
expect(textVal.text().contains("First")}
Using .then() command allows user to switch from Cypress context to jQuery context. Now, user can use any jQuery method to do assertions using chai.js
[https://docs.cypress.io/guides/references/assertions#Chai-jQuery]. Use cy.wrap() to come back to Cypress context and start using cypress commands as usual

Related

Slow performance with Testcafe and ids and custom radio buttons

I have a test where testcafe says "Waiting for element to appear" and I dont understand why.
I use a ID selector
My test is fairly simple and I made a slow version using a ID and a fast one using a non ID
Is this a bug in testcafe?
Using Testcafe v1.11.0 on Chrome 88.0.4324.182 / Windows 10
Test output says:
Book
√ slow (17s)
√ fast (3.69s)
Why is selecting using ID so much slower? Shouldn't it be faster?
This is my test:
import { Selector } from 'testcafe';
fixture('Book').page('https://book.dinnerbooking.com/dk/en-US/book/table/pax/458/2');
test('slow', async t => {
'use strict';
await t
.maximizeWindow()
.click('button.ui-spinner-up')
.click('button.black-button')
.click('#RestaurantAreaConfigAreaId6');
});
test('fast', async t => {
'use strict';
await t
.maximizeWindow()
.click('button.ui-spinner-up')
.click('button.black-button')
.click(new Selector('.restaurant-area-label').nth(1));
});
These two different selectors select two different elements. '#RestaurantAreaConfigAreaId6' selects the <input type="radio" id="RestaurantAreaConfigAreaId6" ... /> element and Selector('.restaurant-area-label').nth(1) selects the <label for="RestaurantAreaConfigAreaId6" class="restaurant-area-label font-large">Café</label> element.
The input element, in turn, is overlapped by another transparent element. In such cases, TestCafe waits until the target element becomes uncovered within the timeout. If the target element stays still, TestCafe clicks on the element above.

TestCafe and grabbing an element/selector when no ID or CSS is present

Hello I have a simple page of our application, the start page that has a disclaimer on it and one button. Because of the technology we are using the IDs are stripped out and obfuscated.
So the button's name is 'ok' as it appears in the page-source view below. Note no ID. Even if I put it in our code, when it is produced the ID is removed.
<div style="text-align:center;">
<input type="button" name="ok" value="Ok" width="40" onclick="swap()" />
</div>
I have the following in my TestCafe js file:
import {Selector } from 'testcafe';
import { ClientFunction } from 'testcafe';
fixture `My fixture`
.page `http://192.168.2.86/mpes/login.jsp`;
test('Disclaimer Page 1', async t => {
const okBtn = Selector('button').withAttribute('ok');
await t
.click(okBtn);
});
test('Disclaimer Page 2 -- of course tried this ', async t => {
await t
.click('ok');
});
.click('ok') -- does not work either
Tried numerous things even trying findElementByName .. but nothing works with Window vs Document and Selector vs element.
Any help would be greatly appreciated.
I have been all over looking at how to grab selectors on TestCafe docs. None seem to fit this scenario which is quite simple -- but highly problematic.
Thanks in advance.
If you want to select this element:
<input type="button" name="ok" value="Ok" width="40" onclick="swap()" />
you can use (one or more) attribute selectors like this:
input[type="button"][name="ok"]
If only one element on the page has the attribute name="ok", you can grab that single element in javascript, using document.querySelector(), like this:
const myButton = document.querySelector('input[type="button"][name="ok"]');
N.B. If multiple elements on the page have the attribute name="ok", you can grab all of them in javascript, using document.querySelectorALL().

Event handling after HTML injection with Vue.js

Vue is not registering event handler for HTML injected objects. How do I do this manually or what is a better way to work around my problem?
Specifically, I send a query to my server to find a token in text and return the context (surrounding text) of that token as it exists in unstructured natural language. The server also goes through the context and finds a list of those words that also happen to be in my token set.
When I render to my page I want all of these found tokens in the list to be clickable so that I can send the text of that token as a new search query. The big problem I am having is my issue does not conform to a template. The clickable text varies in number and positioning.
An example of what I am talking about is that my return may look like:
{
"context": "When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected",
"chunks": ['human events', 'one people', 'political bands']
}
And the resulting output I am looking for is the sentence looks something like this in psuedocode:
When in the Course of <a #click='search("human events")'>human events</a>, it becomes necessary for <a #click='search("one people")'>one people</a> to dissolve the <a #click='search("political bands")'>political bands</a> which have connected
This is what I have tried so far though the click handler is not registered and the function never gets called:
<v-flex xs10 v-html="addlink(context.context, context.chunks)"></v-flex>
and in my methods section:
addlink: function(words, matchterms){
for(var index in matchterms){
var regquery = matchterms[index].replace(this.regEscape, '\\$&');
var query = matchterms[index];
var regEx = new RegExp(regquery, "ig");
words = words.replace(regEx, '<a href=\'#\' v-on:click.prevent=\'doSearch("'+ query +'")\'>' + query + '</a>');
}
return words;
}
As I said, this does not work and I know why. This is just showing that because of the nature of the problem is seems like regex is the correct solution but that gets me into a v-html injection situation. Is there something I can do in Vue to register the event handlers or can some one tell me a better way to load this data so I keep my links inline with the sentence and make them functional as well?
I've already posted one answer but I've just realised that there's a totally different approach that might work depending on your circumstances.
You could use event delegation. So rather than putting click listeners on each <a> you could put a single listener on the wrapper element. Within the listener you could then check whether the clicked element was an <a> (using event.target) and act accordingly.
Here's one way you could approach it:
<template>
<div>
<template v-for="segment in textSegments">
<a v-if="segment.link" href="#" #click.prevent="search(segment.text)">
{{ segment.text }}
</a>
<template v-else>
{{ segment.text }}
</template>
</template>
</div>
</template>
<script>
export default {
data () {
return {
"context": "When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected",
"chunks": ['human events', 'one people', 'political bands']
}
},
computed: {
textSegments () {
const chunks = this.chunks
// This needs escaping correctly
const re = new RegExp('(' + chunks.join('|') + ')', 'gi')
// The filter removes empty strings
const segments = this.context.split(re).filter(text => text)
return segments.map(segment => {
return {
link: segment.match(re),
text: segment
}
})
}
},
methods: {
search (chunk) {
console.log(chunk)
}
}
}
</script>
I've parsed the context text into an array of segments that can then be handled cleanly using Vue's template syntax.
I've used a single RegExp and split, which will not discard matches if you wrap them in a capture group, (...).
Going back to your original example, v-html only supports native HTML, not Vue template syntax. So you can add events using onclick attributes but not #click or v-on:click. However, using onclick wouldn't provide easy access to your search method, which is scoped to your component.

Vue v-model input change mobile chrome not work

If i open https://v2.vuejs.org/v2/guide/forms.html#Text and edit text - no effect on typing text in mobile chrome. #keyup #input #keypress - v-model does not change when I'm typing
<input v-model="message" #keyup="log" placeholder="Edit">
<p>Edited: {{ message }}</p>
How can i fix it? I need get input value on typing (#keyup #input)
Update: After a lot of discussion, I've come to understand that this is a feature, not a bug. v-model is more complicated than you might at first think, and a mobile 'keyboard' is more complicated than a keyboard. This behaviour can surprise, but it's not wrong. Code your #input separately if you want something else.
Houston we might have a problem. Vue does not seem to be doing what it says on the tin. V-model is supposed to update on input, but if we decompose the v-model and code the #input explicitly, it works fine on mobile. (both inputs behave normally in chrome desktop)
For display on mobiles, the issue can be seen at...
https://jsbin.com/juzakis/1
See this github issue.
function doIt(){
var vm = new Vue({
el : '#vueRoot',
data : {message : '',message1 : ''}
})
}
doIt();
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id='vueRoot'>
<h1>v-model</h1>
<div>
<input type='text'
v-model='message'
>
{{message}}
</div>
<h1>Decomposed</h1>
<div>
<input type='text'
:value='message1'
#input='evt=>message1=evt.target.value'
>
{{message1}}
</div>
</div>
I tried all solutions I could find on the internet, nothing worked for me. in the end i came up with this, finally works on android!
Trick is to use compositionupdate event:
<input type="text" ... v-model="myinputbox" #compositionupdate="compositionUpdate($event)">
......
......
methods: {
compositionUpdate: function(event)
{
this.myinputbox = event.data;
},
}
Ok, I dont know if there is another solution for this issue, but it can be solved with a simple directive:
Vue.directive('$model', {
bind: function (el, binding, vnode) {
el.oninput = () => (vnode.context[binding.expression] = el.value)
}
})
using it just like
<input v-$model="{toBind}">
There is an issue on the oficial repo, and they say this is the normal behavior (because the composition mode), but I still need the functionality
EDIT: A simpler solution for me was to just use #input.native. Also, the this event has (now?) a isComposing attribute which we can use to either take $event.data into account, or $event.target.value
In my case, the only scheme that worked was handling #keydown to save the value before the user action, and handling #keyup to process the event if the value had changed. NOTE: the disadvantage of this is that any non-keyboard input (like copy/paste with a mouse) will not work.
<md-input
v-else
:value="myValue"
ref="input"
#keydown="keyDownValue = $event.target.value"
#keyup="handleKeyUp($event)"
#blur="handleBlur()"
/>
With handleKeyUp in my case being:
handleKeyUp(evt){
if(evt.target.value !== this.keyDownValue){
this.$emit('edited', evt);
}
}
My use case was the following:
I requested a search endpoint in the backend to get suggestions as the user typed. Solutions like handling #compositionupdate lead to sending several several requests to the backend (I also needed #input for non-mobile devices). I reduced the number of requests sent by correctly handling #compositionStarted, but there was still cases where 2 requests were sent for just 1 character typed (when composition was left then, e.g. with space character, then re-entered, e.g. with backspace character).

Rails3: how to reload a page with a parameter taken from a collection_select within the page?

I have a page with a route in the form : :client_id/tarif/:tarif_name
in the corresponding HTML page, I have a <%= collection_select(.....:tarif_name...) which enables to select the name of the tarif to be shown. That works.
How do I instruct to reload the page with the new :tarif_name parameter in the url ?
I thought of using the :onchange option helper with collection_select, but although I managed to execute javascript this way, I find no example of composing and triggering the loading of a url through that option.
Thank you very much for your help
If you are able to run javascript code in the :onchange, then window.location.href = "your_url" will make the redirect.
You will also need the selected value. Your onchange will be something like
function() {
window.location.href = "your_url" + this.value
}