How to test window scroll event with vue-testing-library? - vue.js

I want to trigger user interaction for window scroll to change the isScrolled data so that the div class can change. Right now I just test the component when the isScrolled data is changed. Is this the right way to test?

This is acceptable way to test. However, instead of directly setting the isScrolled to true, call the method using the vm as (ensure that you have mocked the document.documentElement.topScroll to something other than zero):
wrapper.vm.onScrollHandler();
Finally, if you need to really test for scroll event, you can manually fire one using the dispatchEvent() method as following:
window.dispatchEvent(new CustomEvent('scroll', { detail: 'anything' }));
You use this and then run your assertion.
On a side note, instead of pictures of your code, paste actual snippets so that they are easy to copy and paste. And, you onScrollHandler can be shortened to:
onScrollHandler() {
this.isScrolled = document.documentElement.topScroll > 0;
}

Related

Revive/activate existing panels

My extension have sidebar webview that can create additional webviews as panels in the active text editor. Each of these additional webviews is for an unique item and I want to revive/activate existing webview, for the specific item, if it exists.
My issues:
I can get a list of the existing tabs with window.tabGroups.all and loop through the result. But there is no way, as far as i can see, to reactivate the desired tab. I can get some properties from there but no methods. The question here is: is there a API to get a list of the tabs and be able to revive/activate it?
Because of the first point ive decided to keep list of the instances of the additional webviews and when new webview is about the be created im checking if its unique id (in the title) is in the list and if it is then just revive the tab instead of creating a new one. Dont like this approach much but its working. The problem here is when the additional webview is closed. When closed it has to be removed from the array. Ive implemented onDidDispose for the panel but somehow the filter function, inside it, is not called:
// panels: vscode.WebviewPanel[]
// create new panel
const panel = vscode.window.createWebviewPanel(...)
// add the webview instance to the panel
const newWebview = new AdditionalWebview(panel, this.context);
this.panels.push(panel);
panel.onDidDispose(() => {
console.log("Before remove the panel"); // can see this in the console
this.panels = this.panels.filter((p) => p.title != panel.title);
console.log("Before remove the panel"); // for some reason this never appears
});
Not sure why but the panel filter functionality is never triggered (and everything after it is also not ran).
extra question: at the moment the uniqueness of the additional panels is based on their label/title. In my case thats is ok but is there any other way to get unique identifier of each tab? id/guid somewhere?
On your first question about activating a given editor, you have a couple of options.
If you know the editor's index/position in its group. That can be obtained from its tabGroup.tabs position - it seems that the tab's index in that array is faithfully its index in the editor. So you could do a Array.findIndex to get the tab uri you want to set to active.
await vscode.commands.executeCommand('workbench.action.openEditorAtIndex', [indexToOpen]);
// note the [] around the index argument
The only problem with this approach is that it works within the active group only, so you may have to activate the correct group first via:
await vscode.commands.executeCommand('workbench.action.focusSecondEditorGroup');
// or whichever group the tab you want to open is in
Or second method:
// assumes you have the tab
const openOptions = { preserveFocus: true, preview: tab.isPreview, viewColumn: tab.group.viewColumn};
// check if a uri, might be viewtype, etc., instead
if (tab.input instanceof vscode.TabInputText) {
await vscode.commands.executeCommand('vscode.open', tab.input.uri, openOptions);
}
// are your editors regular text editors?
This looks like it is opening a new tab but it will focus an existing tab if one exists at that location with that same uri.

how to instantly set/send_keys a textarea in capybara

I need to instantly fill a textarea with a very long string for testing purposes.
set/send_keys simulates typing and is too slow for Sauce Labs causing time outs.
Is there a way to instantly fill a textarea in Capybara?
The only way to instantly do it would be using execute_script to set the value via JS
element = find('textarea') # however you locate the element
execute_script('arguments[0].value = arguments[1]', element, text_to_set)
Note: this won't trigger all the events a user would generate when inputting into the textarea
TL;DR: Use Javascript/JQuery (.val() function) to set the field's value via the .execute_script()/.evaluate_script() function. It will automatically send the full string. You have more details bellow.
Example:
def execute_script(script)
browser.execute(function() {
$('<yourSelectorHere>').val("blablabla");
})
nil
end
Selenium team decided a LOOOONG way back to make it work this way, because it will actually simulate the real way a user would fill that input/textarea/field/etc.
Note: I wrote the command in WebdriverIO, but now have updated to Capybara as well.
Indeed, using the .setValue()/.set(), or the .keys()/.send_keys() methods will issue a POST action on the target element (presumably an <input>) in the form of an array of characters. See example:
Command: browser.setValue('input[connectqa-input="rename-device"]','stackoverflowstackoverflowstack');
Output:
> browser.setValue('input[connectqa-input="rename-device"]','stackoverflowstackoverflowstack')
{ state: 'pending' }
> [21:52:25] COMMAND POST "/wd/hub/session/3d830ffd-21c6-4e5f-a6b3-4f8a03821991/elements"
[21:52:25] DATA {"using":"css selector","value":"input[connectqa-input=\"rename-device\"]"}
[21:52:25] RESULT [{"ELEMENT":"6"}]
[21:52:25] COMMAND POST "/wd/hub/session/3d830ffd-21c6-4e5f-a6b3-4f8a03821991/element/6/clear"
[21:52:25] DATA {}
[21:52:25] COMMAND POST "/wd/hub/session/3d830ffd-21c6-4e5f-a6b3-4f8a03821991/element/6/value"
[21:52:25] DATA {"value":["s","t","a","c","k","o","v","e","r","f","(21 more items)"],"text":"stackoverflowstackoverflowstack"}
One quick and easy way to escape this is to go ahead and abuse the .val() JQuery function via the .execute()/.executeScript() methods:
Command: browser.execute(function() { $('input[connectqa-input="rename-device"]').val("dwadawdawdawdawdawdwadawawdadawdawdaw"); }) (WebdriverIO)
For Capybara syntax, see this question. It covers both .execute_script() & .evaluate_script(). (I don't want to mooch-off their views). Also you should document on the methods before-hand here.
Output:
> [21:59:38] COMMAND POST "/wd/hub/session/3d830ffd-21c6-4e5f-a6b3-4f8a03821991/execute"
[21:59:38] DATA {"script":"return (function () { $('input[connectqa-input=\"rename-device\"]').val(\"dwadawdawdawdawdawdwadawawdadawdawdaw\"); }).apply(null, arguments)","args":[]}
Hope it helped!

web2py SQLFORM accepting too fast

I have a web2py SQLFORM that gets generated and returned by an AJAX call and the form is put in a DIV I defined.. I want that SQLFORM to be an update form, not an insert form. The problem is the form immediately runs it's accept function once it is written to that DIV. This doesn't happen if the form is for inserting, only updating. That initial accept fails and hitting the submit button does not allow for a second accept.
I don't know why the accept fails or why it happens immediately.
heres the JavaScript function that makes the AJAX call
function displayForm(currID){
//Remove everything from the DIV we want to use
$('#window').empty();
//Call the ajax to bring down the form to update the series
ajax('{{=URL('newForm')}}/'+currID,
[], 'window');
}
And here is the newForm controller
def newSerForm():
record = db.myTable(request.args[0])
form = SQLFORM(db.myTable, record, fields=['series_name','image_thumbnail'])
if form.accepts(request.vars,session):
print 'Series update successful!'
else:
print 'Series update Failed...'
return form
displayForm is fired by clicking a button and once you do the form accepts and fails and the submit button doesn't work again. Is there a way to make an SQLFORM do this? The weird thing is if I change this to make inserts into myTable, it works fine. It behaves exactly as it should. But doing it this way doesn't work.
Ok now this is where it gets weird.
I tried to achieve the same functionality here with a totally different approach, an iFrame. I made new functions in my controllers that create the form based on request.args[0]. looks like this
def editEntry():
print request.args[0]
record = db.myTable(request.args[0])
form = SQLFORM(db.CC_user_submission, record, fields=['series_name', 'image_thumbnail']).process()
return dict(form=form)
And then a corresponding HTML page that just displays form. What could be simpler right? I go to that page based on a link that gives the correct argument. Take me to a page with a form for updating. Updating works perfect. Great, now lets put it in an iFrame instead of linking to it. I put it in an iFrame on the original page. Open up the iFrame. Doesn't work. I have no idea what is going is there any part of an explanation to this?
By using the iFrame method I actually got this one to work. Since it required an iFrame to be appended with jQuery which needs quotes and the iFrame URL which also needs quotes, the notation got pretty confusing but it's doable. Looked like this:
var myURL = "{{=URL('editEntry')}}/"+idArg.toString();
$('#window').append("<iframe src = " + myURL + " width='450' height='400'> </iframe>");
It's not pretty but it works.

How to force the parse (only one time ) of a Dojo's button [Err: widget is already registered]

I have a function which adds a button to a div "dettaglio_utenti". After calling the function with this instruction
tab+="<button data-dojo-type='dojox.mobile.Button' id='apri_mappa' onClick=\" location.href='tel:"+telefono+"'\">apri mappa</button>"
var vText = document.getElementById("dettaglio_utente");
vText.innerHTML = tab;
require(["dojo/parser"], function(parser){
parser.parse(vText);
});
It works only the first time that I display the page. The second time the button is not parsed and I see this error in the browser console: dojo/parser::parse() error Error: Tried to register widget with id==apri_mappa but that id is already registered
When you display the page for the second time, the first page must still be part of the dom. (Maybe this is a worklight feature, single page app?). So when dojo parses the second page it gives the error because the button with that id has already been created.
I don't believe preventing the parsing of the button a second time will accomplish what you need. I think your options are:
Destroy the widgets from the first page.
If you don't need an id on the button, you can omit it and Dojo will create an id that won't collide.
If you need the id, you can or use a counter when emitting the id of the button.
id='apri_mappa_' + i where i is the counter.
Only knowing what you wrote above, I think the order of preference is 2,1,3.
EDIT - How to destroy a widget
require(['dijit/registry'], function(registry) {
registry.byId('apri_mappa').destroy();
});

Dojo dnd (drag and drop) 1.7.2 - How to maintain a separate (non-dojo-dnd) list?

I'm using Dojo dnd version 1.7.2 and it's generally working really well. I'm happy.
My app maintains many arrays of items, and as the user drags and drops items around, I need to ensure that my arrays are updated to reflect the contents the user is seeing.
In order to accomplish this, I think I need to run some code around the time of Source.onDndDrop
If I use dojo.connect to set up a handler on my Source for onDndDrop or onDrop, my code seems to get called too late. That is, the source that's passed to the handler doesn't actually have the item in it any more.
This is a problem because I want to call source.getItem(nodes[0].id) to get at the actual data that's being dragged around so I can find it in my arrays and update those arrays to reflect the change the user is making.
Perhaps I'm going about this wrong; and there's a better way?
Ok, I found a good way to do this. A hint was found in this answer to a different question:
https://stackoverflow.com/a/1635554/573110
My successful sequence of calls is basically:
var source = new dojo.dnd.Source( element, creationParams );
var dropHandler = function(source,nodes,copy){
var o = source.getItem(nodes[0].id); // 0 is cool here because singular:true.
// party on o.data ...
this.oldDrop(source,nodes,copy);
}
source.oldDrop = source.onDrop;
source.onDrop = dropHandler;
This ensures that the new implementation of onDrop (dropHandler) is called right before the previously installed one.
Kind'a shooting a blank i guess, there are a few different implementations of the dndSource. But there are a some things one needs to know about the events / checkfunctions that are called during the mouseover / dnddrop.
One approach would be to setup checkAcceptance(source, nodes) for any target you may have. Then keep a reference of the nodes currently dragged. Gets tricky though, with multiple containers that has dynamic contents.
Setup your Source, whilst overriding the checkAcceptance and use a known, (perhaps global) variable to keep track.
var lastReference = null;
var target = dojo.dnd.Source(node, {
checkAcceptance(source, nodes) : function() {
// this is called when 'nodes' are attempted dropped - on mouseover
lastReference = source.getItem(nodes[0].id)
// returning boolean here will either green-light or deny your drop
// use fallback (default) behavior like so:
return this.inhertied(arguments);
}
});
Best approach might just be like this - you get both target and source plus nodes at hand, however you need to find out which is the right stack to look for the node in. I believe it is published at same time as the event (onDrop) youre allready using:
dojo.subscribe("/dnd/drop", function(source, nodes, copy, target) {
// figure out your source container id and target dropzone id
// do stuff with nodes
var itemId = nodes[0].id
}
Available mechanics/topics through dojo.subscribe and events are listed here
http://dojotoolkit.org/reference-guide/1.7/dojo/dnd.html#manager