Rendered component test fails after Ember 1.10 upgrade - ember.js

I'm unit testing a component, in particular the rendered form. I'm approaching this pretty much as described in the Ember Guides.
In particular, the component has three computed properties which show different classes on the rendered elements depending on the backing model. I'm tweaking the properties in Ember.run() blocks and then looking at the rendered component again.
What's interesting here is that the computed properties seem not to be re-computing even through I'm touching the attribute they observe. Later tests which don't test rendering - just the return from the component - do pass.
Here's my test code:
moduleForComponent('wizard-tab', "Component - WizardTab", {
setup: function () {
this.tab = this.subject({ step: 2, stepCompleted: 1, tab: tabs.all()[1] });
}
});
test('#render', function () {
let tab = this.tab;
ok(this.$().find('span.wizard-tab-detail').length, "Active tab has a detail span"); // Passes
// Note that both of the additional states observe stepCompleted
// so I need to touch that to get them to recalculate
Ember.run( function () {
tab.set('stepCompleted', 2);
tab.set('tab', WizardTab.all()[4]);
});
ok(this.$().find('span.wizard-tab-icon-disabled').length, "Future tabs have a disabled class"); // Fails
Ember.run( function () {
tab.set('stepCompleted', 3);
tab.set('tab', WizardTab.all()[1]);
});
ok(this.$().find('span.wizard-tab-icon-done').length, "Inactive tabs have a done class"); // Fails
});
The first assertion passes, the next two fail. Using console.log statements I've validated that the set()s are working, but the property calculated from them is returning the wrong result.
Here's one of the computed property definitions:
disabled: function() {
return this.get('tab.stepNumber') > (this.get('stepCompleted') + 1);
}.property('stepCompleted')
(I literally get false for 5 > 2 when I put in console.log checks on that comparison.) Is there something I'm missing that would prevent that from updating when I check subsequent renders of the component?
This is ember CLI 0.2.0, Ember 1.10.0 and ember-cli-qunit 0.3.8.
ETA: Probably relevant: this test passes on Ember 1.8 and ember-cli-qunit 0.3.1. It's the update to Ember CLI 0.2.0 and accompanying Ember and ember-cli-qunit updates which cause the failure.
(ETA: note from kiwiupover's comment below that this section below isn't relevant to the problem; the guides may not show the best current way to do this.)
Note that the guides use a similar pattern:
test('changing colors', function() {
// this.subject() is available because we used moduleForComponent
var component = this.subject();
// we wrap this with Ember.run because it is an async function
Ember.run(function() {
component.set('name','red');
});
// first call to $() renders the component.
equal(this.$().attr('style'), 'color: red;');
// another async function, so we need to wrap it with Ember.run
Ember.run(function() {
component.set('name', 'green');
});
equal(this.$().attr('style'), 'color: green;');
});
I tried wrapping the second and third assertions in andThen() but that raised errors - andThen() was undefined.

I got this working by starting a new branch off development (our default branch) and re-running the update. Here are the differences between my original pass and what worked:
More component updates, I think just because some time has passed since my first attempt. ember-resolver, loader.js, ember-cli-app-version and ember-cli-dependency-checker had all moved up. I don't know if any of those mattered, but they did change.
The key part, I think, was isolating the three tests in separate test blocks and also updating the subject in an Ember.run() block for each test that used different attribute values from the setup component.
Here's what the three tests looked like when they passed:
moduleForComponent('wizard-tab', "Component - WizardTab", {
setup: function () {
this.tab = this.subject({ step: 2, stepCompleted: 1, tab: WizardTab.all()[1] });
}
});
test('Rendered active tabs have a detail span', function () {
let tab = this.tab;
ok(this.$().find('span.wizard-tab-detail').length, "Active tab has a detail span");
});
test('Rendered future tabs have a disabled class', function () {
let tab = this.tab;
Ember.run( function () {
tab.set('step', 2);
tab.set('stepCompleted', 2);
tab.set('tab', WizardTab.all()[4]);
});
ok(this.$().find('span.wizard-tab-icon-disabled').length, "Future tabs have a disabled class");
});
test('Rendered inactive tabs have a done class', function () {
let tab = this.tab;
Ember.run( function () {
tab.set('step', 2);
tab.set('stepCompleted', 3);
tab.set('tab', WizardTab.all()[1]);
});
ok(this.$().find('span.wizard-tab-icon-done').length, "Inactive tabs have a done class");
});
I believe that last change - moving from one test with some Ember.run() blocks to three - is what really did it. I used some {{log value}} lines in the template to look at which values were being sent to the template, and it was using the subject from the setup block all three times until I added the Ember.run() blocks.

Related

dangerouslyRenderMarkup(...): Cannot render markup in a worker thread [duplicate]

React Tests Fails after set State causes second render
Up until now testing has been going well with JSDOM and Mocha. So far have not had to test any components that change their state. I found my first issue testing a component that changes it's state.
The Error
1) Reduced Test Case - #current Tests that Fail when Component changes state and renders "before each" hook:
Error: Invariant Violation: dangerouslyRenderMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use React.renderToString for server rendering.
at Context.<anonymous> (test/react-reflux/parts/Reduced-spec.js:47:32)
The Component : Reduced.js
var React = require('react');
var Reduced = React.createClass({
getInitialState() {
console.log("start off with editing as false");
return {editing: false};
},
edit() {
console.log("Setting State to Edit");
this.setState({editing: true});
},
render() {
console.log("Rendering");
return (
<span onClick={this.edit}>
{(this.state.editing) ? "Editing" : "Click To Edit"}
</span>
);
}
});
module.exports = Reduced;
The Tests : 1-pass, 1-fail
var React, TestUtils, jsdom, Reduced, expect;
describe('Reduced Test Case', function () {
before(function () {
jsdom = require('jsdom');
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.parentWindow;
React = require('react/addons');
TestUtils = React.addons.TestUtils;
Reduced = require('./Reduced');
expect = require('chai').expect;
this.component = TestUtils.renderIntoDocument(
<Reduced />
);
var root = TestUtils.findRenderedDOMComponentWithTag(this.component, 'span');
this.el = root.getDOMNode();
});
describe("Tests Pass without simulate", function () {
it("Root Element Reads 'Click To Edit'", function () {
expect(this.el.innerHTML).to.equal('Click To Edit');
});
});
describe("Tests that Fail when Component changes state and renders", function () {
beforeEach(function () {
//
// Simulate invokes edit, invokes set state, invokes render, then error occures
//
TestUtils.Simulate.click(this.el);
});
it("Root Element Reads 'Editing'", function () {
expect(this.el.innerHTML).to.equal('Editing');
});
});
});
The Results
> mocha --compilers js:babel/register
Reduced Test Case - #current
start off with editing as false
Rendering
Tests Pass without simulate
✓ Root Element Reads 'Click To Edit'
Tests that Fail when Component changes state and renders
Setting State to Edit
Rendering
1) "before each" hook
1 passing (379ms)
1 failing
1) Reduced Test Case Tests that Fail when Component changes state and renders "before each" hook:
Error: Invariant Violation: dangerouslyRenderMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use React.renderToString for server rendering.
at Context.<anonymous> (test/Reduced-spec.js:47:32)
I've been going crazy
Everything is loaded after global.window and global.document
The Simulate Event invokes edit(), then render() before error
All React Mocha JSDOM tests have been working well until this state change issue
Please help ???
The setup JSDOM setup was missing global.navigator.
global.navigator = {
userAgent: 'node.js'
};
Insert your global object modifying(passing window and document objects to global) before React is required.
Because React creates its ExecutionEnvironment object while required and don't modify it while works.

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)}}`)

Binding 'style' to a computed property

I have a component which is inserted into the DOM as a '' tag (e.g., default behaviour). The component's job is to wrap a 3rd party jQuery tool and I'm trying to ensure it is responsive to "resize" events so I would like to explicitly set width and height style attributes.
In the component, it is easy enough to being to the style attribute:
attributeBindings: ['style'],
style: function() {
return "width: auto";
}.property('widthCalc'),
In this case, this works but doesn't do anything useful because style just returns a static string (width: auto).
Instead what I want to do is -- based on any change to the computed property widthCalc -- set the width based on the new value. So here's the next logical step:
style: function() {
var width = $('body')[0].offsetWidth;
return 'width: ' + width + 'px';
}.property('widthCalc'),
This too works, dynamically setting the DIV to the width of the body's width (note: this isn't really what I want but it does prove that this simple binding works). Now what I really want is to get the value of width from a computed property on the component but I don't even have to go that far to run into trouble; notice that instead of a global jQuery selector I switch to a localised component-scoped selector:
style: function() {
var width = this.$().offsetWidth;
return 'width: ' + width + 'px';
}.property('widthCalc'),
Unfortunately this causes the page NOT to load and gives the following error:
Uncaught Error: Something you did caused a view to re-render after it rendered but before it was inserted into the DOM.
I imagine this is Ember run-loop juju but I'm not sure how to proceed. Any help would be appreciated.
Since it is not possible to call this.$() in the component before it has been added to the dom, provide an initial value until the component is ready.
For example,
Setting a default value to the property style and on didInsertElement event reopen the class and define style as a calculated property using this.$()
http://emberjs.jsbin.com/delexoqize/1/edit?html,js,output
js
App.MyCompComponent = Em.Component.extend({
attributeBindings:["style"],
style:"visibility:hidden",
prop1:null,
initializeThisStyle:function(){
this.set("style","visibility:visible");
this.reopen({
style:function(){
// var thisOffsetWidth = this.$().get(0).offsetWidth;
return "visibility:visible;color:red;background-color:lightgrey;width:"+this.get("prop1")+"px";
}.property("prop1")
});
}.on("didInsertElement")
});
Alternatively handle the error raised by this.$() and provide a default value. Afterwards when the component will be added the property will be calculated as planned.
http://emberjs.jsbin.com/hilalapoce/1/edit?html,js,output
js
App.MyCompComponent = Em.Component.extend({
attributeBindings:["style"],
style:function(){
try{
this.$();//this will throw an erro initialy
return "visibility:visible;color:red;background-color:lightgrey;width:"+this.get("prop1")+"px";
}catch(e){
return "color:blue";
}
}.property("prop1"),
prop1:null
});
With the component I was trying to solve for I ended coming up with an solution that seems effective to me which I will share below. For an understanding of the why I was getting the error and how one might more directly address that error please see the comment from #melc above.
My Solution
What I'm solving for is resizing a jQuery component wrapped in an Ember component. In many cases, resizing is handled gracefully by CSS alone but some jQuery components -- including the very nice knob component from aterrien -- has JS which gets directly involved and therefore needs the containers width and height properties to be set explicitly by the Ember component so that it reacts appropriately.
When solving for this I realised my use-case had two problems:
Solving for a page resize event
Adjusting to the fact that my knob component was -- at times -- in the DOM but in a part of the DOM which was not visible (more explicitly it was in Bootstrap tab which wasn't visible).
The Resize Listener
The first part of the solution is to listen for a page-level resize of the page. I do this with the following:
resizeListener: function() {
var self = this;
self.$(window).on('resize', Ember.run.bind(self, self.resizeDidHappen));
}.on('didInsertElement'),
Page Resize Handler
When a resize is done at the "page" level I now want my component to inspect what the resize impact has been on the component:
resizeDidHappen: function() {
Ember.run.debounce(this, function() {
// get dimensions
var newWidth = Number(this.$().parent().get(0).offsetWidth);
var newHeight = Number(this.$().parent().get(0).offsetHeight);
// set instance variables
this.set('width', newWidth);
this.set('height', newWidth);
// reconfigure knob
this.$('.knob').trigger(
'configure',
{
width: newWidth,
height: newWidth
}
);
}, 300);
}
This solves the page resize problem if it exists in isolation but to make the component it is probably a good idea to solve for the visibility use case as well (certainly in my case it was critical).
Visibility Handler
Why? Well, for two reasons that I can think of:
Many jQuery components refuse to load or perform badly if they aren't loaded
The ember component appears to not be able to establish a "resize" event when it is not visible in the DOM
The one problem is that there is no DOM-level event for visibility changes, so how do we react to a change in visibility without polling on an interval? Well in most cases there will be a UI element which is controlling the state of visibility. In my case it's Bootstrap's tab bar and in this case they have events that fire on the tabs when they become visible. Great. Here's a selector for Bootstrap's selector (assuming you're inside the content area of the newly visible tab):
visibilityEventEmitter: function(context) {
// since there is no specific DOM event for a change in visibility we must rely on
// whatever component is creating this change to notify us via a bespoke event
// this function is setup for a Bootstrap tab pane; for other event emmitters you will have to build your own
try {
var thisTabPane = context.$().closest('.tab-pane').attr('id');
var $emitter = context.$().closest('.tab-content').siblings('[role=tabpanel]').find('li a[aria-controls=' + thisTabPane + ']');
return $emitter;
} catch(e) {
console.log('Problem getting event emitter: %o', e);
}
return false;
},
visibilityEventName: 'shown.bs.tab',
then we just need to add the following code:
_init: function() {
var isVisible = this.$().get(0).offsetWidth > 0;
if (isVisible) {
this.visibilityDidHappen();
}
}.on('didInsertElement'),
visibilityListener: function() {
// Listen for visibility event and signal a resize when it happens
// note: this listener is placed on a DOM element which is assumed
// to always be visibile so no need to wait on placing this listener
var self = this;
Ember.run.schedule('afterRender', function() {
var $selector = self.get('visibilityEventEmitter')(self);
$selector.on(self.get('visibilityEventName'), Ember.run.bind(self, self.visibilityDidHappen ));
});
}.on('didInsertElement'),
visibilityDidHappen: function() {
// On the first visibility event, the component must be initialised
if(!this.get('isInitialised')) {
this.initiateKnob();
} else {
// force a resize assessment as window sizing may have changed
// since last time component was visible
this.resizeDidHappen();
}
},
Note that this also results in a tiny refactor of our resize listener, removing it's trigger from the didInsertElement event and instead being triggered by initiateKnob which will happen not when the Ember component loads but instead lazy load at the first point of visibility in the DOM.
initiateKnob: function() {
var self = this;
this.set('isInitialised', true);
var options = this.buildOptions();
this.$('.knob').knob(options);
this.syncValue();
this.resizeDidHappen(); // get dimensions initialised on load
console.log('setting resize listener for %s', self.elementId);
self.resizeListener(); // add a listener for future resize events
},
resizeListener: function() {
this.$(window).on('resize', Ember.run.bind(this, this.resizeDidHappen));
},
Does it work?
To a large degree but not completely. Here's what works:
the first 'tab' which is visible at load resizes on demand
all tabs resize when they are switched to (aka, when they gain visibility)
what doesn't work is:
tabs other than the first tab do not resize (aka, the onresize callback appears broken)
The error I get is:
vendor.js:13693 Uncaught TypeError: undefined is not a function
Backburner.run vendor.js:13716
Backburner.join vendor.js:34296
run.join vendor.js:34349
run.bind vendor.js:4759
jQuery.event.dispatch vendor.js:4427
jQuery.event.add.elemData.handle
Not sure what to make of this ... any help would be appreciated. Full code can be found here:
https://gist.github.com/295e7e05c3f2ec92fb45.git

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

Ember - Clearing an ArrayProxy

On the Ember MVC TodoApp there is an option "Clear all Completed".
I've been trying to do a simple "Clear All".
I've tried multiple things, none of them work as I expected (clearing the data, the local storage and refreshing the UI).
The ones that comes with the sample is this code below:
clearCompleted: function () {
this.filterProperty(
'completed', true
).forEach(this.removeObject, this);
},
My basic test, that I expected to work was this one:
clearAll: function () {
this.forEach(this.removeObject, this);
},
Though, it's leaving some items behind.
If I click the button that calls this function in the Entries controller a couple times the list ends up being empty. I have no clue what's going on! And don't want to do a 'workaround'.
The clearCompleted works perfectly by the way.
The answer depends on what you really want to know-- if you want to clear an ArrayProxy, as per the question title, you just call clear() on the ArrayProxy instance e.g.:
var stuff = ['apple', 'orange', 'banana'];
var ap = Ember.ArrayProxy.create({ content: Ember.A(stuff) });
ap.get('length'); // => 3
ap.clear();
ap.get('length'); // => 0
This way you're not touching the content property directly and any observers are notified (you'll notice on the TodoMVC example that the screen updates if you type Todos.router.entriesController.clear() in the console).
If you're specifically asking about the TodoMVC Ember example you're at the mercy of the quick and dirty "Store" implementation... if you did as above you'll see when you refresh the page the item's return since there is no binding or observing being done between the entry "controller" and the Store (kinda dumb since it's one of Ember's strengths but meh whatev)
Anywho... a "clearAll" method on the entriesController like you were looking for can be done like this:
clearAll: function() {
this.clear();
this.store.findAll().forEach(this.removeObject, this);
}
Well, this worked:
clearAll: function () {
for (var i = this.content.length - 1; i >= 0; i--) {
this.removeObject(this.content[i]);
}
},
If someone can confirm if it's the right way to do it that would be great!