Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 39 ยท Testing

Acceptance and Unit Tests

Test whole user journeys with visit, currentURL and click, unit-test services, routes and models, and fake the network with a request interceptor for fast, stable tests.

Rendering tests check one component. Acceptance tests check the whole application the way a person uses it: you visit a URL, click links, fill in forms and look at where you end up. Unit tests go the opposite way and check a single class (a service, a util, a model) without any rendering. This lesson covers both, plus the hardest practical question in either: how to keep the network out of your tests.

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

Acceptance tests

An acceptance test boots the real application inside the test page. It uses real routes, templates, components and services, with only the network replaced.

tests/acceptance/login-test.js

JavaScript
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { visit, currentURL, fillIn, click } from '@ember/test-helpers';

module('Acceptance | login', function (hooks) {
  setupApplicationTest(hooks);

  test('a visitor can sign in', async function (assert) {
    await visit('/login');
    assert.strictEqual(currentURL(), '/login');

    await fillIn('[data-test-email]', '[email protected]');
    await fillIn('[data-test-password]', 'secret-pass');
    await click('[data-test-submit]');

    assert.strictEqual(currentURL(), '/dashboard', 'redirected to the dashboard');
    assert.dom('[data-test-welcome]').hasText('Welcome, Ada');
  });

  test('protected pages redirect guests to login', async function (assert) {
    await visit('/dashboard');
    assert.strictEqual(currentURL(), '/login');
  });
});

The new helpers:

Helper Does
visit(url) boots the router at that URL and waits for settledness
currentURL() the URL now (path plus query string)
currentRouteName() the active route name, e.g. posts.post
click, fillIn, ... the same helpers as in rendering tests

Everything runs in the test container, not in a real navigation; visit also resets the app between tests, so one test never starts from another's page.

Name acceptance tests after the journey ("a visitor can sign in"), not the page. They are the slowest tests, so cover the paths that matter most (sign in, purchase, publish) and leave details to rendering and unit tests.

Testing redirects and route guards

The second test above is a route guard check: it proves the beforeModel logic from the session service works together with the router. This is the typical value of an acceptance test: pieces that are individually correct but could be wired wrongly.

You can model that wiring check in plain JavaScript. The mini app below has routes, a guard and a session, and a visit that follows redirects like the real router.

JS Stand-in: visit, redirects and currentURL

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

No output.

Keeping the network out

Acceptance tests that call a real server are slow, flaky and hard to arrange ("what if the database has no posts?"). There are three common ways to take control, from least to most work.

  1. A fake service. Register a FakeSession or FakeApi on this.owner before visit. Simple, but the real network layer (adapters, serializers) goes untested.
  2. A request interceptor. Libraries such as Mirage JS (ember-cli-mirage), MSW, or Pretender intercept fetch/XHR in the browser and answer from handlers you define. Your app code runs unchanged, including Ember Data adapters and serializers.
  3. A real test server. A dedicated test backend. Realistic but slow; keep for a few end-to-end checks.

With Mirage the test defines the data it needs, then visits:

tests/acceptance/posts-test.js

JavaScript
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { setupMirage } from 'ember-cli-mirage/test-support';
import { visit } from '@ember/test-helpers';

module('Acceptance | posts', function (hooks) {
  setupApplicationTest(hooks);
  setupMirage(hooks);

  test('it lists posts from the server', async function (assert) {
    this.server.createList('post', 3);

    await visit('/posts');

    assert.dom('[data-test-post]').exists({ count: 3 });
  });

  test('it shows an error when the server fails', async function (assert) {
    this.server.get('/posts', { message: 'Boom' }, 500);

    await visit('/posts');

    assert.dom('[data-test-error]').exists();
  });
});

The second test is where interceptors shine: forcing a 500 response is one line, whereas with a real server it is nearly impossible. Always test the failure paths: empty lists, 404s, 500s, slow responses.

The stand-in below implements the core of an interceptor: it replaces fetch with a function that answers from a handler table and records the requests, so a test can set up success and failure responses.

JS Stand-in: a fetch interceptor

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

No output.

Unit tests

A unit test uses setupTest and exercises one class through the owner. It is the right tool for logic with many cases: services, utilities, model methods, route redirects.

tests/unit/services/cart-test.js

JavaScript
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Service | cart', function (hooks) {
  setupTest(hooks);

  test('total applies a coupon', function (assert) {
    const cart = this.owner.lookup('service:cart');
    cart.add({ name: 'Notebook', price: 10 });
    cart.add({ name: 'Pen', price: 2 });

    cart.applyCoupon('TEN');

    assert.strictEqual(cart.total, 10.8);
  });

  test('an unknown coupon is rejected', function (assert) {
    const cart = this.owner.lookup('service:cart');
    assert.throws(() => cart.applyCoupon('NOPE'), /Unknown coupon/);
  });
});

Other unit targets:

  • Routes: this.owner.lookup('route:posts') lets you call model() or a guard directly. Often an acceptance test says more.
  • Models (Ember Data): this.owner.lookup('service:store').createRecord('post', {...}) then assert computed properties and validation.
  • Utilities and helpers: import and call the function; no owner needed.
  • Time: inject the clock or use fake timers so tests do not depend on the real time.

Here is the cart test as runnable code, including the arithmetic edge that justifies unit tests: money in floating point.

JS Stand-in: unit-testing money logic

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

No output.

Stubbing time, random and other globals

Tests must not depend on things that change by themselves. Techniques:

  • Pass the clock/random in (as the notifications example did with a fake clock).
  • Use a fake-timer library (for example sinon's fake timers) for code that calls setTimeout directly.
  • Freeze Date.now() in a beforeEach and restore it in afterEach (use hooks.afterEach so it is restored even when a test fails).

What a healthy suite looks like

  • Most tests are unit and rendering tests; acceptance tests cover each key journey once, plus important failure paths.
  • Every test starts from a fresh app and sets up its own data.
  • No real network, no real time, no shared mutable globals.
  • The suite runs in CI on every push with ember test, so regressions are caught before deployment (Build, Addons and Deployment).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an acceptance test exercise that a rendering test does not?

    Acceptance tests boot the full app, visit URLs and follow real navigation, which catches wiring mistakes between parts.
  2. 2. How would you test how the app behaves when the server returns a 500 for /posts?

    Interceptors make failure responses a one-line setup, so error paths can be tested deterministically.
  3. 3. Which helper returns the URL the app is currently at in an acceptance test?

    currentURL() reports the app's router URL (path and query), which is what you assert after navigation and redirects.
  4. 4. Why does the cart total code round money to cents before applying a percentage?

    Binary floating point cannot represent many decimal fractions exactly. Working in cents and rounding avoids surprising totals, and unit tests are where such edge cases get pinned down.

Summary

  • Acceptance tests use setupApplicationTest, visit and currentURL to check complete user journeys, including redirects and guards.
  • Keep the network out: fake services, or a request interceptor like Mirage, MSW or Pretender; always test failure paths.
  • Unit tests use setupTest and this.owner.lookup for services, routes, models and utilities.
  • Control time, randomness and other globals so tests are deterministic.
  • Aim for many fast tests at the bottom and a few acceptance tests for the main journeys.

Next: Ember CLI and the Build Pipeline