ember event trigger order is different in app and tests - ember.js

I have written this simple demo component to demonstrate a problem. The component code is below
App.FocusOutComponent = Em.Component.extend({
attributeBindings: ['tabindex'],
tagName: 'focus-out',
setFocus: function() {
console.log('clicked focus-out container');
this.$().find('button').focus();
console.log('focus set to button');
}.on('click'),
focussedOut: function() {
console.log('focussedOut from outer container');
}.on('focusOut'),
});
{{#focus-out id="focus-container" tabindex="-1"}}
<button id="text-button">Test Button</button>
{{/focus-out}}
When I run this and click on the focus-out element, this is the order of the logs. Link to demo
clicked focus-out container
focussedOut from outer container
focus set to button
Now when I am trying to write acceptance tests for this with the following code.
test('test visit / and click button', function() {
expect(0);
visit('/').then(function() {
find('focus-out').click();
console.log('after click in test');
});
});
The order of the logs are different. Link to demo.
clicked focus-out container
focus set to button
after click in test
focussedOut from outer container
The focusOut log got printed at the very end instead before the after click log. I was expecting the same order for the logs with just an additional log(after click) in the end.
Im not sure if this is a bug or something wrong with my code.
I also noticed another problem while executing tests. If I have focus on the chrome dev-tools while the tests are running, the focusOut event will not trigger at all.
Some help with this is much appreciated.

the click event doesn't set focus (being a back door route). You'll need to manually set focus then click if you want the same results.
Ember's Click Helper (sends mousedown/mouseup, then click)
function click(app, selector, context) {
var $el = app.testHelpers.findWithAssert(selector, context);
run($el, 'mousedown');
if ($el.is(':input')) {
var type = $el.prop('type');
if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') {
run($el, function(){
// Firefox does not trigger the `focusin` event if the window
// does not have focus. If the document doesn't have focus just
// use trigger('focusin') instead.
if (!document.hasFocus || document.hasFocus()) {
this.focus();
} else {
this.trigger('focusin');
}
});
}
}
run($el, 'mouseup');
run($el, 'click');
return app.testHelpers.wait();
}
Modified Test
test('test visit / and click button', function() {
expect(0);
visit('/').then(function() {
var el = find('focus-out');
el.focus();
click(el);
console.log('after click in test');
});
});
http://emberjs.jsbin.com/lefazevozi/1/edit?js,console,output
It's also important to note, that tearing down will also call the focus out event. So the main reason you were seeing the focusout at all was because on teardown it was losing focus from the button child.
Maybe focus should be set before mousedown on the click helper in the ember test, though I'm not sure what else that might affect, or if people wouldn't generally be expecting that since jquery doesn't do that.

Related

Set Focus on slick Slide when foundation reveal modal is opened

Slick keybindings left and right only work when the focus is on a slide. When the reveal modal is opened the focus is not on the slide thus the keybindings wont work. I am looking for a way to either set the focus correctly or set more of a global keybinding but keep in mind there may be more than one gallery on a page. Any suggestions would be greatly appreciated.
$('.galleryGroup').each(function(){
if (typeof $(this).data('gallery') !== 'undefined'){
var id = $(this).data('gallery');
// Open reveal on click
$('.galleriesImage'+id).click(function(){
// Open Reveal Modal
$('#galleriesReveal'+id).foundation('open');
// Cancel Any previously created reveals
$(window).on('closed.zf.reveal',function(){ $('#slides'+id).slick('unslick'); });
// Set the inital slide
if (typeof jQuery(this).data('ref') !== 'undefined'){ var iid=jQuery(this).data('ref'); }else{var iid=0;}
// Initiate slideshow
$('#slides'+id).slick({infinite: true,dots: false,lazyLoad: 'ondemand',autoplay: false,initialSlide: iid});
// Set focus on the slideshow
$('something').focus();
}).css('cursor','pointer');
}
});
With slick it only works when one of the buttons (prev / next) is focused or one of the slides. It does not work when you focus the whole slideshow
$(document).ready(function(){
$(document).foundation();
$('.galleryGroup').each(function(){
if (typeof $(this).data('gallery') !== 'undefined'){
var id = $(this).data('gallery');
// Open reveal on click
$('.galleriesImage'+id).click(function(){
// Open Reveal Modal
$('#galleriesReveal'+id).foundation('open');
// Cancel Any previously created reveals
$(window).on('closed.zf.reveal',function(){ $('#slides'+id).slick('unslick'); });
// Set the inital slide
if (typeof jQuery(this).data('ref') !== 'undefined'){ var iid=jQuery(this).data('ref'); }else{var iid=0;}
// Initiate slideshow
$('#slides'+id).slick({infinite: true,dots: false,lazyLoad: 'ondemand',autoplay: false,initialSlide: iid});
// Set focus on the first slide
//setTimeout(function() {
$('#slides'+id+' .slick-slide').eq(0).focus()
//}, 0);
}).css('cursor','pointer');
}
});
});
In general there are many parts which cna be simplified using the Foundation Sites API and better logic in the code.
https://codepen.io/DanielRuf/pen/RQmPbd

How to test an action gets called in a component ember testing

How can I test that an action was called in a component?
There are multiple ways of triggering an action like clicking on a button. Now I want to test that the action that is called when clicking on that button is actually called. Something like expect.functionName.to.be.called or something.
I have the following code
test('it closes the create dialog when close btn is clicked', function(assert) {
this.render(hbs`{{group-create cancelCreateAction="cancelAction"}}`)
this.$('button.btn--primary').click()
expect('myAction').to.be.called?
})
so i'm just wondering what I can do there?
Well your action does something we don't know. But here's a small test i have written checking some DOM elements and the current route. Hard to tell without you telling us what your action does.
click('.someSavingButton');
andThen(function() {
assert.equal(currentRouteName(), 'index');
assert.equal(find('.something-new-in-the-dom').length, 1, "New item in HTML");
I stumbled upon this question while also searching for a way to test bubble up actions in an integration test (instead
of closure actions). Maybe you already found a solution, but I will answer to have the next person find it earlier than me.
The idiomatic way to test if an action was called is to write a mock function and assert that it will be called.
In your example - before closure actions - the way to write this kind of test is as follows:
test('it closes the create dialog when close btn is clicked', function(assert) {
// make sure our assertion is actually tested
assert.expect(1);
// bind the action in the current test
this.on('cancelAction', (actual) => {
let expected = { whatever: 'you have expected' };
assert.deepEquals(actual, expected);
// or maybe just an assert.ok(true) - but I am not sure if this is "good" style
});
this.render(hbs`{{group-create cancelCreateAction="cancelAction"}}`)
this.$('button.btn--primary').click()
expect('myAction').to.be.called?
});
Nowadays, with the closure action paradigm, the correct way to bind the mock function would be
// bind the action in the current test
this.set('cancelAction', (actual) => {
let expected = { whatever: 'you have expected' };
assert.deepEquals(actual, expected);
});
this.render(hbs`{{group-create cancelCreateAction=(action cancelAction)}}`)

Handling click and doubleclick on same view in emberjs

I have a component which require to handle both click and double click. Its code is like
Template :
<div class="routine_week routine-border box-height-fix fl pointer">
{{mark-down marking}}
</div>
Component
import Ember from 'ember';
export default Ember.Component.extend({
marking : 0,
isMarkable : false,
click : function(){
//click here
},
doubleClick : function(){
//double click here
}
});
Now issue is that doubleClick never got fired. If it does it also fires two click events. How can I ensure that doubleclick event will not interact with click
Ember is so powerful that I was able to imitate DoubleClick using SingleClick event. Its all depend upon Ember.run Loop. Here is the code for anyone like me trying to do that -
//capture event for singleClick only execute if there is no doubleClick
eventIO : null,
//ember actually execute the doubleClick but it also gives two singleClick
doubleClick : function(){
var eventIO = this.get('eventIO');
//check if there is any event for single click, disable it
if(eventIO != null){
Ember.run.cancel(eventIO);
this.set('eventIO',null);
}
// do the stuff with double click
},
// our click event which got executed in both single / double click
click : function(){
var eventIO = this.get('eventIO');
//if this is the first click , schedule it for later after 500 ms
if(eventIO === null)
{
var eventIO = Ember.run.later(this,function(){
//do single click stuff
var eventIO = this.get('eventIO');
///clear additional events
if(eventIO != null){
Ember.run.cancel(eventIO);
this.set('eventIO',null);
}
},500);
//register event to the component
this.set('eventIO',eventIO);
}
},
<p {{on 'dblclick' this.doubleClick}}></p>

Page loading before transition effects happen

I finally got PJAX all setup and working perfect on my Foundation 5 site and its time to add my page transitions. For some reason no matter what I try the page loads and then the transition happens.
Here is my website with with one of the transitions I tried
I've also tried simple things like:
$(document)
.on('pjax:start', function() { $('#main').fadeOut(200); })
.on('pjax:end', function() { $('#main').fadeIn(200); })
I also ran into aenism.com/teleportation-is-scary/ in my searches for a solution and its what I currently have running on my pages.
Here is an example of it working: Demo Site
I'm not sure what the problem could be at this point.
I found a solution that works perfect for fading out and back in again. I have not tested it with other animations but it looks like it should do the trick. I hope this helps someone else!
// USER CLICKS LINK WITH PJAX CLASS
$('body').delegate('a.pjax', 'click', function() {
// CONTENT FADE OUT TRANSITION BEGINS
$('#main-content').fadeOut(300, function() {
// CALLBACK TO RUN PJAX AFTER FADEOUT
$.pjax({
url: target,
container: '#main-content',
fragment: '#main-content'
})
})
// STOP THE LINK FROM WORKING NORMALLY
return false;
})
// PJAX DOIN THANGS TO THE CONTENT FRAGMENT IDENTIFIED ABOVE
$('#main-content')
.on('pjax:start', function() {
// KEEPING THE MAIN CONTENT HIDDEN
$(this).fadeOut(0)
})
.on('pjax:end', function() {
// FADE IN THE MAIN CONTENT
$(this).fadeIn(300)
// FUNCTIONS LOADED AGAIN AFTER PJAX ENDS GO HERE
})
WOOO That suggestion worked, had to tweak it a bunch to get it to fit with my page transitions, but this is what I ended up with (works off of css3 animations):
$("body").delegate('a[data-pjax]', 'click', function(event) {
var target = $(this).attr("href");
if (contentpage == "true" || errorpage == "true") { $(".contentimage").append('<div class="pjax-loading"></div>'); }
$("body").removeClass("pjax-fadeIn").addClass("pjax-fadeOut").one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$.pjax({url: target, container: '#content', fragment: '#content'});
});
return false;
})
$("#content").on('pjax:start', function() {
$("body").removeClass("pjax-fadeOut").addClass("pjax-hide");
}).on('pjax:complete', function() {
$("body").removeClass("pjax-hide").addClass("pjax-fadeIn");
});

AngularJS: how to invoke event handlers and detect bindings in tests

I want to write unit and e2e tests for various custom angularjs directives that add javascript event bindings to the elements they are attached to.
In tests, it's easy enough to simulate click and dblclick events using jQuery methods.
element("#id").click();
However, I am also binding mouseover, mouseout and contextmenu events, and haven't found a way to invoke these in e2e tests. The code below shows the approach I am taking.
it('should show a context menu when the user right clicks on a grid row',
function () {
//not currently triggering the context menu
var outerRow = element(".ngRow", "outer row");
var row = element(".ngRow:first > div", "row");
angular.element(row).triggerHandler("contextmenu");
expect(outerRow.attr("class")).toContain("open");
});
How can I get the contextmenu event to fire in tests?
Similarly, in unit tests for the directives, I want to be able to detect if an event binding has been attached to an element.
How can I achieve this?
Got to the bottom of this eventually. To trigger the events on elements selected using jQuery, jQuery obviously needs to be loaded. The problem is that, as explained here, the Angular runner runs the tests in an IFrame which doesn't have jQuery loaded.
However, you can extend the angular scenario dsl to execute code in the context of your e2e test where jQuery is loaded. The function below enables you execute any javascript method, or to fire any event:
//this function extends the Angular Scenario DSL to enable JQuery functions in e2e tests
angular.scenario.dsl('jqFunction', function () {
return function (selector, functionName /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
return this.addFutureAction(functionName, function ($window, $document, done) {
var $ = $window.$; // jQuery inside the iframe
var elem = $(selector);
if (!elem.length) {
return done('Selector ' + selector + ' did not match any elements.');
}
done(null, elem[functionName].apply(elem, args));
});
};
});
The following code uses the above function to fire the contextmenu event in an e2e test:
it('should show a context menu when the user right clicks on a grid row', function () {
var outerRow = element(".ngRow:first", "outer row");
jqFunction(".ngRow:first > div", "contextmenu");
expect(outerRow.attr("class")).toContain("open");
});