Skip to content

Instantly share code, notes, and snippets.

@cyk
Last active August 29, 2017 19:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyk/e3828d18b26562091447 to your computer and use it in GitHub Desktop.
Save cyk/e3828d18b26562091447 to your computer and use it in GitHub Desktop.
Ember Test Helper: Wait for Change (via MutationObserver)
/**
Ember Test Helper: Wait for Change
Using the MutationObserver API, this helper will wait for an element's contents
to change prior to progressing forward. This is helpful when you are testing
interactions involving async components (ex., Google Maps SDK queries).
@link https://gist.github.com/cyk/e3828d18b26562091447
```javascript
test('user chooses from nearby locations', function(assert) {
visit('/nearby-locations');
// optionally pass target element (defaults to root element)
waitForChange(find('.locations'));
andThen(function() {
click('.location:contains(Oregon)');
ok('.selected-location:contains(Oregon)')
});
});
```
*/
/* global MutationObserver */
import Ember from 'ember';
export default Ember.Test.registerAsyncHelper('waitForChange', function(app, element, timeout) {
var config = {
attributes: true,
childList: true,
characterData: true,
subtree: true
};
element = element || find(':first')[0];
timeout = timeout || 3000;
if (element instanceof Ember.$) {
element = element[0];
}
return Ember.Test.promise(function(resolve, reject) {
Ember.Test.adapter.asyncStart();
var observer = new MutationObserver(function() {
Ember.run(function() {
observer.disconnect();
// Schedule resolution to happen after all DOM element operations
// have completed within the current run loop
Ember.run.schedule('afterRender', null, resolve);
Ember.Test.adapter.asyncEnd();
});
});
observer.observe(element, config);
if (timeout) {
Ember.run.later(null, function() {
Ember.Test.adapter.asyncEnd();
reject();
}, timeout);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment