Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท Testing

Rendering Tests for Components and Helpers

Write Ember rendering tests: render a component, simulate clicks and typing with test helpers, pass arguments and fake services, and check the DOM with qunit-dom.

A rendering test (also called an integration test) answers the question "given these arguments, what does this component show, and what happens when I interact with it?". You render a single component into a test container, drive it with helpers such as click and fillIn, and assert on the DOM. Because it renders only one component and not the whole app, it is fast, but because it uses the real templates and the real browser DOM, it is much closer to reality than a unit test.

This lesson shows the shape of a rendering test, the helpers you will use daily, how to give a component arguments and fake services, and how to test helpers and modifiers. The runnable stand-ins use a tiny fake DOM-free "component" so you can practice the same moves.

Real Ember vs stand-in. File-named blocks are real Ember tests, read-only here (the site cannot run Ember or a browser test runner). Runnable blocks model the ideas in plain JavaScript.

The shape of a rendering test

tests/integration/components/counter-test.gjs

JavaScript
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click } from '@ember/test-helpers';
import Counter from 'my-app/components/counter';

module('Integration | Component | counter', function (hooks) {
  setupRenderingTest(hooks);

  test('it counts clicks', async function (assert) {
    await render(<template><Counter /></template>);

    assert.dom('button').hasText('Clicked 0 times');

    await click('button');
    await click('button');

    assert.dom('button').hasText('Clicked 2 times');
  });
});

Reading it from the top:

  1. setupRenderingTest(hooks) creates a fresh app and a container element for each test.
  2. render(<template>...</template>) renders a template written inline. In the .gjs/.gts test files of current Ember you import the component and use it directly; older projects use hbs from ember-cli-htmlbars with a string, which still works.
  3. await click(...) clicks and waits until the app is settled (see Testing Ember Apps), so the next line sees the updated DOM.
  4. assert.dom(...) checks what the user would see.

Always await the helpers. A forgotten await is the most common cause of "the assertion ran too early".

The helpers you will use most

All come from @ember/test-helpers.

Helper Does
render(template) renders the template into the test container
click(selector) click an element (fires mousedown, focus, mouseup, click)
fillIn(selector, text) set an input's value and fire input and change
typeIn(selector, text) type character by character (fires key events)
select(selector, value) choose an option in a <select>
triggerEvent(selector, 'mouseenter') dispatch any DOM event
triggerKeyEvent(selector, 'keydown', 'Enter') press a key
focus(selector) / blur(selector) move focus
find(selector) / findAll(selector) get elements from the test container
waitFor(selector) wait for an element to appear (for work outside the settled world)
settled() wait until no work is pending
rerender() flush a render without waiting for all async work

The selectors are scoped to the test container, so click('button') never hits something outside the component.

Arguments, blocks and callbacks

Pass arguments inline, with the same syntax as a real template:

JavaScript
test('it greets by name', async function (assert) {
  await render(<template><Greeting @name="Ada" /></template>);
  assert.dom('[data-test-greeting]').hasText('Hello, Ada!');
});

To test callbacks the component calls, pass a function and use QUnit steps (no mocking library needed):

JavaScript
test('it calls onSave with the form data', async function (assert) {
  const save = (data) => assert.step(`saved ${data.title}`);

  await render(<template><PostForm @onSave={{save}} /></template>);
  await fillIn('[data-test-title]', 'Hello Ember');
  await click('[data-test-submit]');

  assert.verifySteps(['saved Hello Ember']);
});

assert.verifySteps fails if the callback was not called, called twice, or called with something else, and the failure lists exactly what happened.

For components that take blocks, include the block in the inline template:

JavaScript
await render(<template>
  <Card as |card|>
    <card.title>Hello</card.title>
  </Card>
</template>);

Services in rendering tests

By default a component under test gets the real services. That is fine for simple services. When a service calls a server or the clock, register a fake before rendering; because lookups go through the owner (Dependency Injection) the component never notices:

JavaScript
import Service from '@ember/service';

class FakeSession extends Service {
  user = { name: 'Test User' };
  isAuthenticated = true;
}

test('it shows the signed-in user', async function (assert) {
  this.owner.register('service:session', FakeSession);

  await render(<template><UserMenu /></template>);

  assert.dom('[data-test-user]').hasText('Test User');
});

To check that a component used a service, spy by giving the fake a method that records steps:

JavaScript
class FakeNotifications extends Service {
  add(text) {
    this.lastMessage = text;
  }
}
// ...after interacting:
assert.strictEqual(this.owner.lookup('service:notifications').lastMessage, 'Saved');

Testing a form without the framework

The stand-in below does not use Ember or a DOM; it models a small form component as a function from state to a text "screen", plus click and fillIn helpers that mimic the test helpers. The point is the testing pattern: render, interact, assert the visible result, and use steps to check callbacks.

JS Stand-in: render, fillIn, click and verifySteps

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Testing helpers and modifiers

A helper is a pure function used in templates, so you can test it in two ways: call the function directly in a unit test, or render it:

JavaScript
import { formatPrice } from 'my-app/helpers/format-price';

test('formatPrice formats cents', async function (assert) {
  assert.strictEqual(formatPrice(1999), '$19.99');

  await render(<template><span data-test-price>{{formatPrice 1999}}</span></template>);
  assert.dom('[data-test-price]').hasText('$19.99');
});

When the helper is plain, the pure function test is usually enough, and it is the fastest.

A modifier attaches behavior to an element, so render an element that uses it and check the effect:

JavaScript
await render(<template><input {{autofocus}} data-test-input /></template>);
assert.dom('[data-test-input]').isFocused();

Here is the pure-function style for a helper, runnable. Edge cases such as zero, negatives and rounding are exactly what a helper's tests should cover.

JS Stand-in: testing a formatting helper

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Accessibility checks

The ember-a11y-testing addon adds a11yAudit(), which runs the axe rules against the rendered DOM, so a rendering test can fail when a button has no accessible name or an image lacks alt text:

JavaScript
import a11yAudit from 'ember-a11y-testing/test-support/audit';

test('it is accessible', async function (assert) {
  await render(<template><PostForm /></template>);
  await a11yAudit();
  assert.true(true, 'no a11y violations');
});

Cheap to add and catches a surprising number of real problems.

Common mistakes

  • Missing await before a helper: the assertion runs before the DOM updates.
  • Asserting too much in one test: when the title says "it shows the greeting", it should not also check the footer.
  • Using classes as selectors: prefer data-test-*.
  • Real network in tests: stub with a fake service or a request interceptor (next lesson) so tests are fast and deterministic.
  • Testing implementation details, such as a private method, instead of the visible result.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must you await helpers such as click and fillIn?

    The awaited promise includes waiting for rendering and pending async work. Without it the assertion runs too early.
  2. 2. A component calls this.args.onSave(data). How can a rendering test check it was called once with the right data?

    Steps record each call in order, and verifySteps fails if the calls differ from what you expected.
  3. 3. How do you replace the session service with a fake in a rendering test?

    Components look services up through the owner, so a registration made before rendering is what they receive.
  4. 4. Which test is best for a pure formatting helper with many edge cases?

    A pure function needs no rendering to be tested well, and direct calls make many cases fast to write.

Summary

  • A rendering test renders one component with setupRenderingTest, render, then drives and asserts it.
  • Use click, fillIn, select, triggerEvent and always await them.
  • Pass arguments and callbacks inline; check callbacks with assert.step and verifySteps.
  • Register fake services on this.owner before rendering.
  • Test pure helpers by calling them directly; test modifiers through an element that uses them.
  • Add a11yAudit() for cheap accessibility coverage.

Next: Acceptance and Unit Tests