Ember: Testing WillDestroyElement Logic of Component in an Integration Test - javascript

I have an Ember component...
Ember.Component.extend({
onDidInsertElement: function(){
var that = this;
Ember.run.scheduleOnce('afterRender', () => {
// Some code that sets up a jQuery plugin which attaches events etc
});
},
onWillDestroyElement: function(){
// Code that destroys the jQuery plugin (removing attached events etc)
}
}
Here's my integration test:
test('it renders', function (assert) {
this.render(hbs`{{my-component }}`);
// Here some code to make sure the rendered state is ok
// then...
// ?? How to fire the "willDestroyElement" lifecycle hook?
}
Assuming I know how to check for the existence of the jQuery plugin events on the page (e.g. using the technique described here), how do I actually test the teardown logic in my integration test?

You can use component.destroyElement (which mentions it will invoke willDestroyElement hook) or component.destroy.
Approach to do that without accessing component instance:
this.set('showComponent', true);
this.render(hbs(`{{if showComponent}}{{my-component}}{{/if}}`));
Then set:
this.set('showComponent', false);

Related

Webdriver.io : Wait for method

I have a problem in my automatic test scenario when I try to call my function costumtra using webdriver.io.
I want that the scenario waits until the method call finish
describe('senario', function() {
it('can click submit button', function() {
// Do something
browser.costumtra(browser.element('#submit'));
// Do something
}
});
browser.addCommand("costumtra", function(element) {
// Do something
}
any solution please ?
You can define custom commands at any point in your test suite, just make sure that the command is defined before you first use it (the before hook in your wdio.conf.js might be a good point to create them). Also to note: custom commands, like all WebdriverIO commmands, can only be called inside a test hook or it block. May be your are calling the test method before define it. change it as given below.
browser.addCommand("costumtra", function(element) {
// Do something
}
describe('senario', function() {
it('can click submit button', function() {
// Do something
browser.costumtra(browser.element('#submit'));
// Do something
}
});

Testing event handlers

I have an event handler that modifies some global variable based on the click action. How can I test it? For example:
function initEvent() {
function enable() {
var arr = Context.get('arr');
arr.push('aaa');
};
function disable() {
var arr = Context.get('arr');
arr.push('bbb');
};
$('#content').on('click', '#element', function () {
if (this.checked) {
enable();
} else {
disable();
}
});
};
This is the function I am calling after the HTML has been rendered. It calls enable() and disable() functions based on the user action. I want to test these functions and check if they behave correctly. How can I do that?
You want to test your code. You should never test code with console.log or alert. These are great to debug something on the fly, but they are not test tools. These promote manual testing, where you need to manually run the code and see that pass, that's horrible time waste.
You should use Jasmine in this case (you can use other testing frameworks, though Jasmine is super easy) to test your code. You can setup browser tests or headless tests, which is out of the scope of this question, there are tons of tutorials on the subject.
Now, in order to test this code, I assume that the Context has a static method get which returns an array which is on the Context IIFE scope. If the case is different feel free to fiddle around with the specs and make it serve your needs, or alternatively if you get stuck, update this question or ask another one on Stackoverflow.
I have setup Jasmine, with jasmine-fixture to test your code, the jQuery click event behavior. In this plunk you will find everything you need.
I am using the browser to test the code, so I need jasmine's html reporter.
The real tests are in script-spec.js, where I am using Jasmine's API, by describing a spec suite (with describe) and defining each spec with it method.
In beforeEach I prepare the code to run before each spec executes. Essentially here, I create a simple div with #content id and a child input element of type checkbox with #element id. I do this by using the
setFixtures('<div id="content"><input type="checkbox" id="element" /></div>');
Which is a method jasmine-fixture library provides.
Now I can test the code, wiring up the specs:
it("Should return an array with 'aaa' element when #element is checked", function() {
// Arrange
initEvent();
var checkbox = $("#content").find("#element");
// Act
checkbox.click();
// Assert
expect(Context.get('arr').length).toBe(1);
expect(Context.get('arr')).toEqual(['aaa']);
});
I run the initEvent method and get a reference of the checkbox element. In Act section I click the element manually, marking it as checked, which is the normal behavior. In Assert, I test the Context.get('arr') return value.
Again, link to plunk is here.
Hope this helps.
One simple test you can do to test enable, disable and the click handler is to create a function that checks the contents of arr in Context, and call it after each of the functions within the click handler that add something to arr.
The general way to test conditions in your code is with assertions which will throw an error if the condition you pass into them is false. You can use console.assert just for that:
$('#content').on('click', '#element', function() {
if (this.checked) {
enable();
// assert last element in `arr` is the enabled string 'aaa'
console.assert(
Context.get('arr')[Context.get('arr').length - 1] === 'aaa',
'enable() works'
);
} else {
disable();
// assert last element in `arr` is the disabled string 'bbb'
console.assert(
Context.get('arr')[Context.get('arr').length - 1] === 'bbb',
'disable() works'
);
}
});
If any of the tests run after you click your element, you know initEvent assigned the click handler and it works. Then, you just toggle the checked flag to test enable()/disable() as well.
If there are no errors in your browser console, the tests have passed. Otherwise, there will be an error in your console containing the message passed as the second argument to console.assert.
You could even make a helper function to simplify the testing a bit:
function assertLastElementInContextArr(elem, msg) {
var arr = Context.get('arr');
// assert last item in `arr` is equal to `elem`
console.assert(arr[arr.length - 1] === elem, msg);
}
$('#content').on('click', '#element', function() {
if (this.checked) {
enable();
// assert last element in `arr` is the enabled string 'aaa'
assertLastElementInContextArr('aaa', 'enable() works');
} else {
disable();
// assert last element in `arr` is the disabled string 'bbb'
assertLastElementInContextArr('bbb', 'disable() works');
}
});
EDIT based on your comment
But how do I mock the click event? I mean, I want to automatically test all those events, no I have to somehow trigger the click automatically. How do I do that?
If you want to programmatically invoke click events, you can use JS to trigger them in code. Since you're using jQuery, it already comes with a method trigger to do just that.
All you need to do is:
$('#content').trigger('click')
And it will activate your click handler and run the assertions tests from above.
In fact, jQuery even comes with aliased handlers for specific events so you can just do:
$('#content').click();
To automate the testing, you can create a function that will trigger the clicks and set the checked state as well, to test both cases.
function test(checked) {
var elem = $('#content');
elem.prop('checked', checked);
elem.click();
}
Important thing to be careful about is that these events will happen asynchronously so you must do something to manage a proper testing order if you're going to trigger multiple clicks. Otherwise you will set checked to true, trigger the click and then run the second test that will set checked to false before the click events even happen.
For demonstration purposes, here's one way to safely test multiple successive clicks by adding an event handler just for testing and removing it once you're done. One requirement for this to work is to attach the handler after all your other handlers have been attached, to make sure the test handler runs last. Additionally, you can run your assertions here as well to not pollute your code and keep the testing fully separated:
function test(checked, value, msg, done) {
var elem = $('#content');
elem.prop('checked', checked);
// attach a test event handler and trigger the click
elem.on('click', testClick);
elem.click();
// once the click is executed,
// remove the test handler,
// run the assertions and then
// call the callback to signal the test is done
function testClick() {
elem.off('click', runTest);
assertLastElementInContextArr(value, msg);
done();
}
}
// run your code before the tests
initEvent();
// test enable(), then once that's done, test disable()
test(true, 'aaa', 'enable() works', function() {
test(false, 'bbb', 'disable() works', function() {
console.log('All tests finished');
});
});
If you're going to be testing your entire app like this, you'd probably want to use a test framework like QUnit, Mocha, Jasmine which will handle all these async issues for you and give you a nice API to work with.
Just add console.log(<some variable>) or alert(<some variable>) at function calls. e.g.:
function initEvent() {
function enable() {
alert("enable called!");
var arr = Context.get('arr');
arr.push('aaa');
};
function disable() {
alert("disable called!");
var arr = Context.get('arr');
arr.push('bbb');
};
$('#content').on('click', '#element', function () {
alert("click occured!");
if (this.checked) {
enable();
} else {
disable();
}
});
};
Or use your browsers developer tools setting breakpoints at these spots.

How to cover Marionette View's event using test cases of Jasmine?

I am working on Test cases for Marionette's View. By using events attribute, I have written a callback function on click of an HTML element. The functionality is working but I am struggling in writing test cases. I am not able to cover that click event using Jasmine test cases.
I have used the Marionette Region to render the view.
I have tried using spies but those are not working.
Please find code below for more details:
var TestView = Backbone.Marionette.CompositeView.extend({
tagName: 'div',
className: 'test-menu',
childView: testMenuView,
childViewOptions: function() {
return {
'componentId': this.cid
};
},
template: _.template(testTemplate),
initialize: function(options) {
this.collection = this.options.testData;
},
onShow: function(collectionView) {
collectionView.$el.show();
},
attachHtml: function(collectionView,itemView) {
collectionView.$("#testMenu").append(itemView.el);
},
events: {
'click #testBtn': function (event) {
alert('testBtn Clicked');
}
}
});
I like to use JQuery where I can when I write tests due to it being less verbose, and for most events triggering the handlers with JQuery will also work fine.
Given that you've got everything else set up for running a Jasmine suite I'd do
it('reacts to click events on its button', function() {
var view = new TestView();
view.render();
view.$('#testBtn').click(); // or view.$('#testBtn').trigger('click')
//(verify that the view did what was expected)
});
If testing the alert is the actual problem then use a spy for that, e.g. spyOn(window, 'alert') and expect(window.alert).ToHaveBeenCalledWith('testBtn Clicked')
JQuery won't always be able to trigger event handlers that are bound with addEventListener. Click is not one of those events, but there are situations where I have to trigger events using for examples
var event = document.createEvent('Event');
event.initEvent('keydown');
event.keyCode = 40;
event.altKey = true;
view.el.querySelector('input').dispatchEvent(event);
But most of the time just using JQuery's .trigger or corresponding shortcut-function directly on the element you want is fine.

Jasmine - How can I mock history.pushState and also fake event emission?

I'm writing a library that supports browser navigation with the help of history.pushState and also catches the popstate event that communicates when navigation takes place in the browser. As I'm trying to write Jasmine tests for this library, I'm wondering how I can mock history.pushState and also fake the emission of the popstate signal from window? The following code snippets should elucidate the problem:
Library code:
var lib = (function() {
function navigate(path) {
history.pushState(null, null, path);
}
function onPopState(event) {
if (lib.callback) {
lib.callback(document.location);
}
}
$(window).bind('popstate', onPopState);
return {
navigate: navigate
};
})();
Test code (Jasmine):
describe("Test navigate", function() {
it("Should invoke callback upon state change", function() {
var invokedWith;
function callback(url) {
invokedWith = url;
}
lib.callback = callback;
lib.navigate('/path');
// Doesn't work, callback invoked asynchronously
expect(invokedWith).toEqual('/path');
});
});
Basically, I want to mock the history.pushState function and emit a fake popstate event from window, so as to test the popstate handling in lib.
See also my fiddle for "working" code.
You can spy on history.pushState like this:
spyOn(history, 'pushState');
As you use jquery to bind the event you can simply trigger popstate by yourself.
$(window).trigger('popstate')

How to unit test this code

I googled on how to unit test but examples are so simple. the examples always show functions that return something or do ajax that returns something - but never have i seen examples that do callbacks, nested callbacks and functions that are "one-way", that they just store something and never return anything.
say i have a code like this, how should i go about testing it?
(function(){
var cache = {};
function dependencyLoader(dependencies,callback2){
//loads a script to the page, and notes it in the cache
if(allLoaded){
callback2()
}
}
function moduleLoader(dependencies, callback1){
dependencyLoader(dependencies,function(){
//do some setup
callback1()
});
}
window.framework = {
moduleLoader : moduleLoader
}
}());
framework.moduleLoader(['foo','bar','baz'],function(){
//call when all is loaded
})
This illustrates a problem with keeping things private in an anonymous function in javascript. It's a bit difficult to validate that things are working internally.
If this was done test first then the cache, dependencyLoader and moduleLoader should be publicly available on the framework object. Or else it would be difficult to validate that the cache was handled properly.
To get things going I'd recommend you take a gander on BDD, that conveniently gives you an approach to help you start by letting you spell out the behaviour with a given-when-then convention. I like to use Jasmine, which is a javascript BDD framework (that integrates with jstestdriver), for this kind of thing and the unit tests I'd make for the sample you have above would be:
describe('given the moduleloader is clear', function() {
beforeEach(function() {
// clear cache
// remove script tag
});
describe('when one dependency is loaded', function() {
beforeEach(function() {
// load a dependency
});
it('then should be in cache', function() {
// check the cache
});
it('then should be in a script tag', function() {
// check the script tag
});
describe('when the same dependency is loaded', function() {
beforeEach(function () {
// attempt to load the same dependency again
});
it('then should only occur once in cache', function() {
// validate it only occurs once in the cache
});
it('then should only occur once in script tag', function() {
// validate it only occurs once in the script tag
});
});
});
// I let the exercise of writing tests for loading multiple modules to the OP
});
Hope these tests are self explanatory. I tend to rewrite the tests so that they nest nicely, and usually the actual calls are done in the beforeEach functions while the validation are done in the it functions.

Categories

Resources