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

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");
});

Related

Test functions passed as props to modal in React Redux

I am looking for a way to test the functions passed as props to a React Bootstrap modal in React Redux, generated in a similar way to here: https://stackoverflow.com/a/35641680/4401847.
I need to test functions passed as props through mapDispatchToProps/mergeProps with Chai and Mocha. The way I'm trying to do so is by dispatching actions which make the modal pop up
This would be an example of a test case, at least its first lines:
it("should dispatch an action when clicking a button", function (done) {
store.dispatch({
type: "modal/show",
modalType: "POST",
modalProps: {
mode: "add",
title "Create new post"
}
});
const modal = mount(<Provider store={store}><PostModal/><Provider/>);
setTimeOut(function() {
//I don't know how to access the functions passed as props via dispatchToProps and mergeProps.
});
});
Thank you very much

ember event trigger order is different in app and tests

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.

How do I trigger a keyup/keydown event in an angularjs unit test?

I want to unit test a directive that emulates a placeholder, where the input value is cleared only on keyup/down events.
You need to create an event programatically and trigger it. To do so including jQuery for unit tests is quite useful. For example, you could write a simple utility like this:
var triggerKeyDown = function (element, keyCode) {
var e = $.Event("keydown");
e.which = keyCode;
element.trigger(e);
};
and then use it in your unit test like so:
triggerKeyDown(element, 13);
You can see this technique in action in the http://angular-ui.github.io/bootstrap/ project here: https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/test/typeahead.spec.js
Disclaimer: let's be precise here: I'm not advocating using jQuery with AngularJS! I'm just saying that it is a useful DOM manipulation utility for writing tests interacting with the DOM.
To make the above code work without jQuery, change:
$.Event('keydown')
to:
angular.element.Event('keydown')
I had issues with using accepted answer. I found other soultion.
var e = new window.KeyboardEvent('keydown', {
bubbles: true,
cancelable: true,
shiftKey: true
});
delete e.keyCode;
Object.defineProperty(e, 'keyCode', {'value': 27});
$document[0].dispatchEvent(e);
Working example can be found here
I got something like this working.
element.triggerHandler({type:"keydown", which:keyCode});
if you are using angular2, you can trigger any event by calling dispatchEvent(new Event('mousedown')) on HTMLElement instance. for example: Tested with angular 2.rc1
it('should ...', async(inject([TestComponentBuilder], (tcb:TestComponentBuilder) => {
return tcb.createAsync(TestComponent).then((fixture: ComponentFixture<any>) => {
fixture.detectChanges();
let com = fixture.componentInstance;
/* query your component to select element*/
let div:HTMLElement = fixture.nativeElement.querySelector('div');
/* If you want to test #output you can subscribe to its event*/
com.resizeTest.subscribe((x:any)=>{
expect(x).toBe('someValue');
});
/* If you want to test some component internal you can register an event listener*/
div.addEventListener('click',(x)=>{
expect(x).toBe('someOtherValue');
});
/* if you want to trigger an event on selected HTMLElement*/
div.dispatchEvent(new Event('mousedown'));
/* For click events you can use this short form*/
div.click();
fixture.detectChanges();
});
I recently wanted to test this HostListener on a component (Angular 2):
#HostListener('keydown.esc') onEsc() {
this.componentCloseFn();
};
And after searching for some time, this is working:
..
nativeElement.dispatchEvent(new KeyboardEvent('keydown', {'key': 'Escape'}));
...

Testing jQuery UI "Dialog" logic using Jasmine

In my JS view-code I am using a jQuery UI Dialog component to render a popup.
I instantiate it like this:
var popupDialog = $("#myPopupDiv").dialog({
title: "My dialog",
dialogClass: "myDialogClass",
create: createHandler,
draggable: false,
width: width,
height: height,
autoOpen: false
});
Notice it's got autoOpen set to "false". I open it in the "create"-handler:
var createHandler = function(event, ui) {
//Vi venter litt for å sikre at popupen er "klar"
setTimeout(function () {
popupDialog.dialog("open");
}, 5);
};
The open-logic is wrapped in a setTimeout to ensure the popup is ready.
The code works fine in app the browser, but when I run this code using Jasmine test-framework I get an error:
Error: cannot call methods on dialog prior to initialization; attempted to call method 'open'
The test actually passes, so clearly the item is rendered. But I don't like the error showing up when I run the tests!
I suspect that since the Jasmine tests run so fast, the component has not had time to initialize itself. So how can I assure that the component is initialized? I thought putting this logic in the "create"-handler would take care of that since that event is "Triggered when the dialog is created.", but clearly that is not the case.
Here is how I test it:
it("should show my popup", function () {
var myPopupLink = $('.popupLink');
myPopupLink.click();
//Wait until popup is shown
waitsFor(function () {
return !$('.myDialogClass').is(":hidden");
}, "Popupen didn't show", 1000);
//Check that the DOM is as expected
expect($('.myDialogClass .popupContentDiv')).toExist();
expect(...
//Close popup
myPopupLink.click();
expect($('.myDialogClass .popupContentDiv')).not.toExist();
});
Anybody have a clue how I can verify the initialization-status of the popup-dialog?
Or any other workarounds?
Thanks!
The problem with your test is, that it is more an acceptance test then a unit test. Most of stuff that you try to test is functionality of jQueryUi. What you really wanna test is that the createHandler opened the dialog with a delay. So your popupDialog.dialog should be a spy where you can check that it was called after the delay.
At the moment your code is really hard to test cause it is based directly on jquery. You should think about to have functions where you can inject your depenedencies instead of relying on global variables like popupDialog.
Here is an example on how to mock out all dependencies:
//mock out setTimeout so you dont have to wait in your test
jasmine.Clock.useMock();
//create a mock that will return from $().dialog()
var mockDialog = jasmine.createSpy('dialog');
// mock $ to return {dialog: mock that return {dialog: mockDialog}}
var mock$ = spyOn(window, '$').andReturn({
dialog:jasmine.createSpy('$').andReturn({
dialog: mockDialog
})
})
expect(mock$).toHaveBeenCalled();
// call the create function
window[mock$.mostRecentCall.args[0].create]();
jasmine.Clock.tick(4999);
expect(mockDialog$).not.toHaveBeenCalled();
jasmine.Clock.tick(5001);
expect(mockDialog$).toHaveBeenCalledWith('open');
As you can see its very complicated to mock out all the jQuery dependencies. So ether you rewrite your code for better testability or test this stuff as acceptance test with selenium capybara etc.

angularjs triggerHandler is not firing binded event in unit test

with angularJs 1.0.2 I created simple directive that binds to click event on element.
I tried to unittest it with testacular
var linked;
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
var widget_definition = 'click here';
linked = $compile(widget_definition);
}));
it('chceck logic on click', function() {
var button = linked(scope);
// this doesnt work so I give up :/
button.triggerHandler('click');
});
but it tells me that there is no such function defined on button element. but this is already jQ(lite) object and in other tests I can use methods defined for jQlite.
is this a bug in angular??
triggerHandler was added in 1.0.3
Here's a JSFiddle that doesn't throw an exeception http://jsfiddle.net/jaimem/c5Tfw/1/
btw, if you are dealing with UI changes you might want to do e2e tests.