Last active
August 29, 2017 19:38
-
-
Save cyk/e3828d18b26562091447 to your computer and use it in GitHub Desktop.
Ember Test Helper: Wait for Change (via MutationObserver)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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