I have a component that integrates 2 third-party libraries, imagesLoaded and Isotope.
I get conflicting test failures when running tests in the browser and cli mode. The error is:
Error: Assertion Failed: You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in a run
or
TypeError: 'undefined' is not an object (evaluating 'self.$().isotope')
When I try to wrap callbacks in an ember run loop, they pass in cli-mode, but then fail in browser mode. I can't seem to find the right combination. The issue seems to happen in the callback of imagesLoaded, as if I remove that plugin, it seems to pass fine.
I've tried multiple combinations, but here is my latest code. If anyone has insight on how to properly use the run loop in this component, that would be helpful.
handleLoad: function() {
let self = this;
Ember.run.scheduleOnce('afterRender', this, function(){
self.$().imagesLoaded( function() {
Ember.run(function() {
self.$().isotope({itemSelector: ".card-container"});
self.$().isotope('shuffle');
});
}); // imagesLoaded
}); // Ember.run
}.on('didInsertElement')
You'll have to wrap your existing code in a
Ember.run(function () {
// Ember.run.scheduleOnce('afterRender....
});
as this tells Ember where the run loop starts and ends - in production/development this is done for you by Ember itself, but in testing you have to wrap it.
As an alternative you can start & end a run loop manually by calling it explicitly (see the API Docs):
Ember.run.begin() // <-- tell Ember that your starting a run loop
//Ember.run.scheduleOnce('afterRender', ...
//more ember run loops here
Ember.run.end(); // <-- tell Ember that the run loop ends here
Related
This is repeated a few times in the current Ember documentation, so I feel like I must be missing something. Let's take the simplest example I found.
Why is the call to levelUp considered asynchronous to warrant wrapping it in the run loop?
incrementProperty is synchronous, and as far as I can tell, so is set (but I could be mistaken here)
player.js
import DS from 'ember-data';
export default DS.Model.extend({
level: DS.attr('number', { defaultValue: 0 }),
levelName: DS.attr('string', { defaultValue: 'Noob' }),
levelUp() {
let newLevel = this.incrementProperty('level');
if (newLevel === 5) {
this.set('levelName', 'Professional');
}
}
});
player-test.js
import { moduleForModel, test } from 'ember-qunit';
import Ember from 'ember';
moduleForModel('player', 'Unit | Model | player', {
// Specify the other units that are required for this test.
needs: []
});
test('should increment level when told to', function(assert) {
// this.subject aliases the createRecord method on the model
const player = this.subject({ level: 4 });
// wrap asynchronous call in run loop
Ember.run(() => player.levelUp());
assert.equal(player.get('level'), 5, 'level gets incremented');
assert.equal(player.get('levelName'), 'Professional', 'new level is called professional');
});
First of all, you are absolutely right. It is not well-described anywhere in the guides.
In testing mode, autorun is disabled. You can read further from the guides about this.
But changing the value in model triggers a run-loop. You can see that at this twiddle. The result is:
Assertion Failed: You have turned on testing mode, which disabled the
run-loop's autorun. You will need to wrap any code with asynchronous
side-effects in a run
(By the way, both set and incrementProperty trigger this run-loop as your guess.)
Then here is the run loop source:
DS.attr returns a computed property with set.
The set function triggers an event.
At the end, a run loop is triggered.
#ykaragol is absolutely right about his explanation within his correct answer and I have nothing to add why you need to wrap your code within a run loop; because the source code is there and emberRun.schedule is being called, which requires a run-loop.
What I would like to explain is a bit more about the assertion error you get: "You have turned on testing mode, which disabled the run-loop's autorun. You will need to wrap any code with asynchronous side-effects in a run". That does not directly mean an asynchronous operation (in the sense that an ajax call is made, or a timer is triggered) is in place. We are mostly unaware but; Ember.js does use Ember.run loops and various run queues such as sync, actions, render, afterRender, etc. in order to schedule the effects of our codes so as to optimize the rendering of our application. Even if the code this.set('levelName', 'Professional'); does seem like pretty synchronous; Ember wraps it within a run-loop so that the computed property calculation, or other updates are buffered together in order to prevent multiple rendering (hence decreased performance) of the templates.
I only wished there was better explanation about both run loop, run queues, or how and why to use run loops within tests, but there is not :(
So my acceptance test keeps on destroying itself before my promise finishes. I'm aware that I need to wrap my promise in Ember run loop but I just can't get it to work. Here's how my component looks:
export default Ember.Component.extend({
store: Ember.inject.service(),
didReceiveAttrs() {
this.handleSearchQueryChange();
},
/**
* Search based on the searchQuery
*/
handleSearchQueryChange() {
this.get('store').query('animals', {
orderBy: 'name',
startAt: this.attrs.searchQuery
}).then(searchResults => {
this.set('searchResults', searchResults);
});
}
});
I've already tried wrapping this.handleSearchQueryChange(), this.get('store').query... and this.set('searchResults', searchResults) in a run loop but still, the acceptance test just doesn't wait for store.query to finish.
One thing to note that this store query performs a request on a live Firebase back-end.
I'm currently using Pretender to mock the data and solve this issue. But I'd like to solve it through Ember.run as well. Anyone care to provide a solution?
It sounds like your problem may have the same cause as the errors I've been seeing
tl;dr
To work around this issue, I've been using a custom test waiter. You can install it with ember install ember-cli-test-model-waiter (for Ember v2.0+) and it should just make your test work without any further setup (if not, please file a bug).
Longer answer:
The root cause of this problem is that the ember testing system doesn't know how to handle Firebase's asynchronicity. With most adapters, this isn't a problem, because the testing system instruments AJAX calls and ensures they have completed before proceeding, but this doesn't work with Firebase's websockets communication.
The custom test waiter I mentioned above works by waiting for all models to resolve before proceeding with the test, and so should work with any non-AJAX adapter.
I am trying to get some tests to pass for an ember addon. It was working fine until yesterday I added some code that runs later in the run loops using Em.run.next.
Here is what Im doing in my test.
visit('/').then(function() {
find('bm-select').click();
andThen(function() {
equal(1,1, 'yay');
});
});
The problem is when click is triggered, the later function is executed after andThen. By that time all my tests are done and it throws error. I am under the impression andThen should wait for all async stuff to finish.
This is what what my code looks like when click is triggered(focusOut event is triggered on click)
lostFocus: function() {
if(this.get('isOpen')) {
Em.run.later(this, function() {
var focussedElement = document.activeElement;
var isFocussedOut =
this.$().has(focussedElement).length === 0 && !this.$().is(focussedElement);
if(isFocussedOut) {
this.closeOptions({focus:false});
}
}, 0);
}
}.on('focusOut'),
You can see that it gives an error Uncaught TypeError: Cannot read property 'has' of undefined. This is from the focusOut method. By the time the function executes the components _state is 'destroying' and this.$() returns undefined.
I tried the wait helper and still I am not able to get the tests to work. How is this normally done.
I have extracted the tests to run in a bin. Here is the link to it.
After further debugging, the problem is one of tags 'bm-select' has it focusOut event triggered in the teardown method of testing. So by the time the run loop code executes the component is not inDOM.
I just added a hidden input field in the test app. Once I've run all the tests, I set focus to the hidden input field and use the wait test helper. Now all the run loop code is done by the time the tear down method is executed.
working in ember-cli testing. After all tests passed it returns extra two test with errors.
Uncaught Error: Assertion Failed: calling set on destroyed object
Source : '../dist/assets/vendor.js:13269'
this is one unit test configuration
import Ember from "ember";
import { test,moduleFor } from 'ember-qunit';
import startApp from '../helpers/start-app';
var App;
module('An Integration test',{
setup:function(){
App=startApp();
},
teardown: function() {
Ember.run(App, 'destroy');
}
});
This is either because in the result of a promise or any other deferred code you do not check the destroy status of an object, or because you didn't teardown something that has been setup and interact with DOM events or anything external to the core of Ember.
I used to have this especially on some jQuery plugins which I mapped to Ember, and during the tests the plugins were destroying too slowly and I was then either not using a run loop, or not checking the destroyed status of the Ember object I was manipulating.
You can do so with:
if ( !(obj.get('isDestroyed') || obj.get('isDestroying')) ) {
// do your destroying code setting stuff
}
Also think about destroying any jQuery plugins that might have been initialised in the code of your views (anything setup in didInsertElement should be teardown in willDestroyElement for example).
Ok i struggled with similar thing. So basically when you have "this.set()" inside a promise, it might happen that the promise takes too long to resolve, and the user already clicked away from that page, in this case you are trying to set something, that is already destroyed. I found the simplest solution to be just a simple check in the beginning of the promise.
if (this.isDestroyed) {
return;
}
this.set('...');
...
Edit: alternatively you can use Ember.trySet.
The issue is related to a promise not completely resolving and another test getting run immediately after.
You should give Ember Concurrency a try.
import { task, timeout } from 'ember-concurrency';
myFunction: task(function * () {
// do somethinng
yield timeout(1000); // wait for x milliseconds
// do something else
}).drop(),
I had a similar issue in an integration test. To resolve, in the integration test, I waited before performing the next action.
import wait from 'ember-test-helpers/wait';
wait().then(() => {
// perform action (which previously used to cause an exception)
});
I'm testing an relatively large Ember application (http://wheelmap.org/map) with QUnit and having problems with debounced calls e.g. changing the url to have a permalink of a map view inside the app or doing a manual AJAX request while testing.
I followed the documentation at http://emberjs.com/guides/testing/integration/
Now when I reset the application state by calling App.reset() in the module setup it resets all bindings, etc. to variables and dependant controllers.
module('Map', {
setup: function() {
App.reset();
}
});
This seems to be good to have a clean working environment, but leads to errors where variables are accessiable by Ember.set and Ember.get e.g. this.get('controllers.toolbar'):
Cannot call method 'set' of null
So the first test allways runs great, but further tests break because of debounced function calls from the first test. So what I think I have to do is stop this debounced calls somehow.
Other options would be checking if all needed variables are set in this function calls. But this seems to be cumbersome when adding conditions only for testing.
What do you think?
Thank you in advance!
I found the answer by searching through the RunLoop source files:
Ember.run.cancelTimers()
It's not part of the documentation. Maybe a problem of poor documentation or not beeing part of the public API.
Now I just call it in the module test teardown function:
module('Map', {
setup: function() {
// ...
},
teardown: function() {
Ember.run.cancelTimers()
}
});
We ran into a similar problem and decided to disable debounce during testing.
You can check if in testing mode using if(Ember.testing){...}.