- DOM Interaction Helpers
- DOM Query Helpers
- Routing Helpers
- Rendering Helpers
- Wait Helpers
- Pause Helpers
- Debug Helpers
- Test Framework APIs
Unfocus the specified target.
Sends a number of events intending to simulate a "real" user unfocusing an element.
The following events are triggered (in order):
blur
focusout
The exact listing of events that are triggered may change over time as needed to continue to emulate how actual browsers handle unfocusing a given element.
target
(string | Element) the element or selector to unfocus (optional, defaultdocument.activeElement
)
Emulating blurring an input using blur
blur('input');
Returns Promise<void> resolves when settled
Clicks on the specified target.
Sends a number of events intending to simulate a "real" user clicking on an element.
For non-focusable elements the following events are triggered (in order):
mousedown
mouseup
click
For focusable (e.g. form control) elements the following events are triggered (in order):
mousedown
focus
focusin
mouseup
click
The exact listing of events that are triggered may change over time as needed to continue to emulate how actual browsers handle clicking a given element.
Use the options
hash to change the parameters of the MouseEvents.
You can use this to specifiy modifier keys as well.
target
(string | Element) the element or selector to click onoptions
Object the options to be merged into the mouse events (optional, default{}
)
Emulating clicking a button using click
click('button');
Emulating clicking a button and pressing the shift
key simultaneously using click
with options
.
click('button', { shiftKey: true });
Returns Promise<void> resolves when settled
Double-clicks on the specified target.
Sends a number of events intending to simulate a "real" user clicking on an element.
For non-focusable elements the following events are triggered (in order):
mousedown
mouseup
click
mousedown
mouseup
click
dblclick
For focusable (e.g. form control) elements the following events are triggered (in order):
mousedown
focus
focusin
mouseup
click
mousedown
mouseup
click
dblclick
The exact listing of events that are triggered may change over time as needed to continue to emulate how actual browsers handle clicking a given element.
Use the options
hash to change the parameters of the MouseEvents.
target
(string | Element) the element or selector to double-click onoptions
Object the options to be merged into the mouse events (optional, default{}
)
Emulating double clicking a button using doubleClick
doubleClick('button');
Emulating double clicking a button and pressing the shift
key simultaneously using click
with options
.
doubleClick('button', { shiftKey: true });
Returns Promise<void> resolves when settled
Fill the provided text into the value
property (or set .innerHTML
when
the target is a content editable element) then trigger change
and input
events on the specified target.
target
(string | Element) the element or selector to enter text intotext
string the text to fill into the target element
Emulating filling an input with text using fillIn
fillIn('input', 'hello world');
Returns Promise<void> resolves when the application is settled
Focus the specified target.
Sends a number of events intending to simulate a "real" user focusing an element.
The following events are triggered (in order):
focus
focusin
The exact listing of events that are triggered may change over time as needed to continue to emulate how actual browsers handle focusing a given element.
Emulating focusing an input using focus
focus('input');
Returns Promise<void> resolves when the application is settled
Taps on the specified target.
Sends a number of events intending to simulate a "real" user tapping on an element.
For non-focusable elements the following events are triggered (in order):
touchstart
touchend
mousedown
mouseup
click
For focusable (e.g. form control) elements the following events are triggered (in order):
touchstart
touchend
mousedown
focus
focusin
mouseup
click
The exact listing of events that are triggered may change over time as needed to continue to emulate how actual browsers handle tapping on a given element.
Use the options
hash to change the parameters of the tap events.
target
(string | Element) the element or selector to tap onoptions
Object the options to be merged into the touch events (optional, default{}
)
Emulating tapping a button using tap
tap('button');
Returns Promise<void> resolves when settled
Triggers an event on the specified target.
target
(string | Element) the element or selector to trigger the event oneventType
string the type of event to triggeroptions
Object additional properties to be set on the event
Using triggerEvent to Upload a file
When using triggerEvent to upload a file the eventType
must be change
and you must pass the
options
param as an object with a key files
containing an array of
Blob.
triggerEvent(
'input.fileUpload',
'change',
[new Blob(['Ember Rules!'])]
);
Returns Promise<void> resolves when the application is settled
Triggers a keyboard event of given type in the target element.
It also requires the developer to provide either a string with the key
or the numeric keyCode
of the pressed key.
Optionally the user can also provide a POJO with extra modifiers for the event.
target
(string | Element) the element or selector to trigger the event oneventType
("keydown"
|"keyup"
|"keypress"
) the type of event to triggerkey
(number | string) thekeyCode
(number) orkey
(string) of the event being triggeredmodifiers
Object? the state of various modifier keys (optional, defaultDEFAULT_MODIFIERS
)modifiers.ctrlKey
boolean if true the generated event will indicate the control key was pressed during the key event (optional, defaultfalse
)modifiers.altKey
boolean if true the generated event will indicate the alt key was pressed during the key event (optional, defaultfalse
)modifiers.shiftKey
boolean if true the generated event will indicate the shift key was pressed during the key event (optional, defaultfalse
)modifiers.metaKey
boolean if true the generated event will indicate the meta key was pressed during the key event (optional, defaultfalse
)
Emulating pressing the ENTER
key on a button using triggerKeyEvent
triggerKeyEvent('button', 'keydown', 'Enter');
Returns Promise<void> resolves when the application is settled
Mimics character by character entry into the target input
or textarea
element.
Allows for simulation of slow entry by passing an optional millisecond delay between key events.
The major difference between typeIn
and fillIn
is that typeIn
triggers
keyboard events as well as input
and change
.
Typically this looks like focus
-> focusin
-> keydown
-> keypress
-> keyup
-> input
-> change
per character of the passed text (this may vary on some browsers).
target
(string | Element) the element or selector to enter text intotext
string the test to fill the element withoptions
Object {delay: x} (default 50) number of milliseconds to wait per keypress (optional, default{}
)
Emulating typing in an input using typeIn
typeIn('hello world');
Returns Promise<void> resolves when the application is settled
Find the first element matched by the given selector. Equivalent to calling
querySelector()
on the test root element.
selector
string the selector to search for
Returns Element matched element or null
Find all elements matched by the given selector. Similar to calling
querySelectorAll()
on the test root element, but returns an array instead
of a NodeList
.
selector
string the selector to search for
Returns Array array of matched elements
Get the root element of the application under test (usually #ember-testing
)
Returns Element the root element
Navigate the application to the provided URL.
Returns Promise<void> resolves when settled
Returns string the currently active route name
Returns string the applications current url
Renders the provided template and appends it to the DOM.
template
CompiledTemplate the template to render
Returns Promise<void> resolves when settled
Clears any templates previously rendered. This is commonly used for
confirming behavior that is triggered by teardown (e.g.
willDestroyElement
).
Returns Promise<void> resolves when settled
Used to wait for a particular selector to appear in the DOM. Due to the fact that it does not wait for general settledness, this is quite useful for testing interim DOM states (e.g. loading states, pending promises, etc).
selector
string the selector to wait foroptions
Object? the options to be used (optional, default{}
)
Returns Promise<(Element | Array<Element>)> resolves when the element(s) appear on the page
Wait for the provided callback to return a truthy value.
This does not leverage settled()
, and as such can be used to manage async
while not settled (e.g. "loading" or "pending" states).
callback
Function the callback to use for testing when waiting should stopoptions
Object? options used to override defaults (optional, default{}
)
Returns Promise resolves with the callback value when it returns a truthy value
Returns a promise that resolves when in a settled state (see isSettled
for
a definition of "settled state").
Returns Promise<void> resolves when settled
Checks various settledness metrics (via getSettledState()
) to determine if things are settled or not.
Settled generally means that there are no pending timers, no pending waiters, no pending AJAX requests, and no current run loop. However, new settledness metrics may be added and used as they become available.
Returns boolean true
if settled, false
otherwise
Check various settledness metrics, and return an object with the following properties:
hasRunLoop
- Checks if a run-loop has been started. If it has, this will betrue
otherwise it will befalse
.hasPendingTimers
- Checks if there are scheduled timers in the run-loop. These pending timers are primarily registered byEmber.run.schedule
. If there are pending timers, this will betrue
, otherwisefalse
.hasPendingWaiters
- Checks if any registered test waiters are still pending (e.g. the waiter returnstrue
). If there are pending waiters, this will betrue
, otherwisefalse
.hasPendingRequests
- Checks if there are pending AJAX requests (based onajaxSend
/ajaxComplete
events triggered byjQuery.ajax
). If there are pending requests, this will betrue
, otherwisefalse
.hasPendingTransitions
- Checks if there are pending route transitions. If the router has not been instantiated / setup for the test yet this will returnnull
, if there are pending transitions, this will betrue
, otherwisefalse
.pendingRequestCount
- The count of pending AJAX requests.debugInfo
- Debug information that's combined with info return from backburner's getDebugInfo method.
Returns Object object with properties for each of the metrics used to determine settledness
Returns a promise to be used to pauses the current test (due to being returned from the test itself). This is useful for debugging while testing or for test-driving. It allows you to inspect the state of your application at any point.
The test framework wrapper (e.g. ember-qunit
or ember-mocha
) should
ensure that when pauseTest()
is used, any framework specific test timeouts
are disabled.
Usage via ember-qunit
import { setupRenderingTest } from 'ember-qunit';
import { render, click, pauseTest } from '@ember/test-helpers';
module('awesome-sauce', function(hooks) {
setupRenderingTest(hooks);
test('does something awesome', async function(assert) {
await render(hbs`{{awesome-sauce}}`);
// added here to visualize / interact with the DOM prior
// to the interaction below
await pauseTest();
click('.some-selector');
assert.equal(this.element.textContent, 'this sauce is awesome!');
});
});
Returns Promise<void> resolves only when resumeTest()
is invoked
Resumes a test previously paused by await pauseTest()
.
Retrieves debug information from backburner's current deferred actions queue (runloop instance).
If the getDebugInfo
method isn't available, it returns null
.
Returns (MaybeDebugInfo | null) Backburner debugInfo or, if the getDebugInfo method is not present, null
Registers a custom debug info helper to augment the output for test isolation validation.
debugHelper
DebugInfoHelper a custom debug info helper
import { registerDebugInfoHelper } from '@ember/test-helpers';
registerDebugInfoHelper({
name: 'Date override detection',
log() {
if (dateIsOverridden()) {
console.log(this.name);
console.log('The date object has been overridden');
}
}
})
Stores the provided resolver instance so that tests being ran can resolve objects in the same way as a normal application.
Used by setupContext
and setupRenderingContext
as a fallback when setApplication
was not used.
resolver
Ember.Resolver the resolver to be used for testing
Retrieve the resolver instance stored by setResolver
.
Returns Ember.Resolver the previously stored resolver
Used by test framework addons to setup the provided context for testing.
Responsible for:
- sets the "global testing context" to the provided context (
setContext
) - create an owner object and set it on the provided context (e.g.
this.owner
) - setup
this.set
,this.setProperties
,this.get
, andthis.getProperties
to the provided context - setting up AJAX listeners
- setting up
pauseTest
(also available asthis.pauseTest()
) andresumeTest
helpers
context
Object the context to setupoptions
Object? options used to override defaults (optional, default{}
)options.resolver
Resolver? a resolver to use for customizing normal resolution
Returns Promise<Object> resolves with the context that was setup
Retrive the "global testing context" as stored by setContext
.
Returns Object the previously stored testing context
Stores the provided context as the "global testing context".
Generally setup automatically by setupContext
.
context
Object the context to use
Clear the "global testing context".
Generally invoked from teardownContext
.
Used by test framework addons to tear down the provided context after testing is completed.
Responsible for:
- un-setting the "global testing context" (
unsetContext
) - destroy the contexts owner object
- remove AJAX listeners
context
Object the context to setupoptions
Object? options used to override defaultsoptions.waitForSettled
boolean should the teardown wait forsettled()
ness (optional, defaulttrue
)
Returns Promise<void> resolves when settled
Used by test framework addons to setup the provided context for rendering.
setupContext
must have been ran on the provided context
prior to calling setupRenderingContext
.
Responsible for:
- Setup the basic framework used for rendering by the
render
helper. - Ensuring the event dispatcher is properly setup.
- Setting
this.element
to the root element of the testing container (things rendered viarender
will go into this element).
context
Object the context to setup for rendering
Returns Promise<Object> resolves with the context that was setup
Used by test framework addons to tear down the provided context after testing is completed.
Responsible for:
- resetting the
ember-testing-container
to its original state (the value whensetupRenderingContext
was called).
context
Object the context to setupoptions
Object? options used to override defaultsoptions.waitForSettled
boolean should the teardown wait forsettled()
ness (optional, defaulttrue
)
Returns Promise<void> resolves when settled
Retrieve the application instance stored by setApplication
.
Returns Ember.Application the previously stored application instance under test
Stores the provided application instance so that tests being ran will be aware of the application under test.
- Required by
setupApplicationContext
method. - Used by
setupContext
andsetupRenderingContext
when present.
application
Ember.Application the application that will be tested
Used by test framework addons to setup the provided context for working with an application (e.g. routing).
setupContext
must have been run on the provided context prior to calling
setupApplicationContext
.
Sets up the basic framework used by application tests.
context
Object the context to setup
Returns Promise<Object> resolves with the context that was setup
Used by test framework addons to tear down the provided context after testing is completed.
context
Object the context to setupoptions
Object? options used to override defaultsoptions.waitForSettled
boolean should the teardown wait forsettled()
ness (optional, defaulttrue
)
Returns Promise<void> resolves when settled
Validate the provided error handler to confirm that it properly re-throws
errors when Ember.testing
is true.
This is intended to be used by test framework hosts (or other libraries) to
ensure that Ember.onerror
is properly configured. Without a check like
this, Ember.onerror
could easily swallow all errors and make it seem
like everything is just fine (and have green tests) when in reality
everything is on fire...
callback
Function the callback to validate (optional, defaultEmber.onerror
)
Example implementation for ember-qunit
import { validateErrorHandler } from '@ember/test-helpers';
test('Ember.onerror is functioning properly', function(assert) {
let result = validateErrorHandler();
assert.ok(result.isValid, result.message);
});
Returns Object object with isValid
and message
Sets the Ember.onerror
function for tests. This value is intended to be reset after
each test to ensure correct test isolation. To reset, you should simply call setupOnerror
without an onError
argument.
onError
Function the onError function to be set on Ember.onerror
Example implementation for ember-qunit
or ember-mocha
import { setupOnerror } from '@ember/test-helpers';
test('Ember.onerror is stubbed properly', function(assert) {
setupOnerror(function(err) {
assert.ok(err);
});
});
Resets Ember.onerror
to the value it originally was at the start of the test run.
import { resetOnerror } from '@ember/test-helpers';
QUnit.testDone(function() {
resetOnerror();
})