Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 39 ยท Projects and Practice

Project: Building a Test Suite

Practice test-driven development in Ember: write unit, rendering and acceptance tests for the notes app, use fakes for storage and time, and run a runnable test plan.

In this project you write the tests for the notes app. It is deliberately a testing project, not a feature project: the app already works, and your job is to prove that it does, in a way that will catch mistakes in the future. You will plan the suite, write unit tests for the service, rendering tests for the editor, and one acceptance test for the main journey, following the structure from Testing Ember Apps.

Real Ember vs stand-in. The Ember test files are real code shown read-only, since the site cannot run Ember's test runner. The runnable examples run the same logic tests against plain JavaScript versions of the service, with a tiny test runner, so you can practice writing good assertions.

Step 1: write the test plan

Start with a list of behaviors, not with code. A test plan for the notes app might be:

Level Behavior Why this level
Unit (service) creating a note adds it and gives it a new id pure logic, fast
Unit search matches title and body, case-insensitively many cases
Unit pinned notes sort first; ties sort by newest ordering rules
Unit notes survive a reload; corrupt storage starts empty persistence
Rendering (editor) typing in the title updates the note DOM events
Rendering the Pin button toggles its label DOM state
Acceptance create a note, edit it, pin it, find it by search whole journey
Acceptance opening /notes/999 redirects to the list routing guard

Notice the proportions: many unit tests, a few rendering tests, two acceptance tests. Each behavior is tested once, at the lowest level that can check it.

Step 2: make the service easy to test

The service from the notes app calls localStorage and Date.now() directly. Both make tests awkward: storage leaks between tests and times differ on every run. The cure is to depend on something you can replace. In Ember, that is a fake registered on the owner; for storage a small wrapper service works well:

app/services/storage.js

JavaScript
import Service from '@ember/service';

export default class StorageService extends Service {
  getItem(key) {
    try {
      return localStorage.getItem(key);
    } catch {
      return null;
    }
  }

  setItem(key, value) {
    try {
      localStorage.setItem(key, value);
    } catch {
      // unavailable: ignore
    }
  }
}

The notes service then injects it (@service storage;) and calls this.storage.getItem(...). In tests, register a memory version:

tests/helpers/fake-storage.js

JavaScript
import Service from '@ember/service';

export default class FakeStorage extends Service {
  data = new Map();
  getItem(key) {
    return this.data.get(key) ?? null;
  }
  setItem(key, value) {
    this.data.set(key, value);
  }
}

Step 3: unit tests for the service

tests/unit/services/notes-test.js

JavaScript
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import FakeStorage from '../../helpers/fake-storage';

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

  hooks.beforeEach(function () {
    this.owner.register('service:storage', FakeStorage);
    this.notes = this.owner.lookup('service:notes');
  });

  test('create adds a note with a fresh id', function (assert) {
    const a = this.notes.create();
    const b = this.notes.create();
    assert.notStrictEqual(a.id, b.id);
    assert.strictEqual(this.notes.all.length, 2);
  });

  test('search matches title and body, ignoring case', function (assert) {
    this.notes.create().title = 'Shopping list';
    const second = this.notes.create();
    second.title = 'Idea';
    second.body = 'Buy TEA';

    this.notes.query = 'tea';
    assert.deepEqual(this.notes.visible.map((n) => n.title), ['Idea']);
  });

  test('pinned notes come first', function (assert) {
    const first = this.notes.create();
    first.title = 'First';
    const second = this.notes.create();
    second.title = 'Second';
    first.pinned = true;

    assert.deepEqual(this.notes.visible.map((n) => n.title), ['First', 'Second']);
  });

  test('notes are restored from storage', function (assert) {
    this.notes.create().title = 'Remember me';
    this.notes.save();

    const storage = this.owner.lookup('service:storage');
    assert.true(storage.getItem('notes-app:v1').includes('Remember me'));
  });
});

Each test creates a fresh owner, so this.notes starts empty every time, and the registered FakeStorage replaces the real one. No test can interfere with another.

Step 4: a runnable version of the same plan

To practice writing assertions you can run, here is the service under test (storage and clock injected) together with a small test runner and the plan's unit tests. Add your own cases at the bottom, especially edge cases: what about an empty query with spaces, two notes with the same timestamp, or removing a note that does not exist?

JS Unit tests for the notes logic, runnable

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

No output.

A test that never fails proves little. Try changing the sort in visible and watch which tests catch it. That is how you check that your tests actually guard the behavior.

Step 5: rendering tests for the editor

tests/integration/components/note-editor-test.gjs

JavaScript
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, fillIn, click } from '@ember/test-helpers';
import NoteEditor from 'notes-app/components/note-editor';
import Note from 'notes-app/utils/note';
import FakeStorage from '../../helpers/fake-storage';

module('Integration | Component | note-editor', function (hooks) {
  setupRenderingTest(hooks);

  hooks.beforeEach(function () {
    this.owner.register('service:storage', FakeStorage);
    this.note = new Note({ id: 1, title: 'Draft' });
  });

  test('typing updates the title', async function (assert) {
    const note = this.note;
    await render(<template><NoteEditor @note={{note}} /></template>);

    await fillIn('[data-test-title]', 'Final');

    assert.strictEqual(note.title, 'Final');
  });

  test('the pin button toggles its label', async function (assert) {
    const note = this.note;
    await render(<template><NoteEditor @note={{note}} /></template>);

    assert.dom('[data-test-pin]').hasText('Pin');
    await click('[data-test-pin]');
    assert.dom('[data-test-pin]').hasText('Unpin');
  });
});

Two small tests, each with one clear purpose. The label test also proves the template reacts to a tracked field.

Step 6: one acceptance test

tests/acceptance/notes-test.js

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

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

  hooks.beforeEach(function () {
    this.owner.register('service:storage', FakeStorage);
  });

  test('create, edit, pin and find a note', async function (assert) {
    await visit('/notes');
    await click('[data-test-new]');
    assert.ok(currentURL().startsWith('/notes/'), 'opened the new note');

    await fillIn('[data-test-title]', 'Tea ritual');
    await click('[data-test-pin]');

    await visit('/notes');
    await fillIn('[data-test-search]', 'tea');

    assert.dom('[data-test-note]').exists({ count: 1 });
    assert.dom('[data-test-note]').hasText(/Tea ritual/);
  });

  test('an unknown note redirects to the list', async function (assert) {
    await visit('/notes/999');
    assert.strictEqual(currentURL(), '/notes');
  });
});

This is the only place that proves the pieces are connected: routes, components and service working together.

Step 7: review your suite

A short checklist to evaluate any suite you write:

  • Independent: can each test run alone and in any order?
  • Deterministic: no real time, network or storage; a failure always means a real bug.
  • Readable: the test name says the behavior; the body has setup, action, assertion.
  • Focused: one reason to fail per test.
  • Valuable: if you broke the feature, would a test fail? (Try breaking it on purpose.)
  • Fast: unit tests in milliseconds; only acceptance tests need the whole app.

Then run ember test in CI on every push, as in Deploying Ember Apps.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why wrap localStorage in its own storage service for this project?

    A replaceable storage dependency means tests control what is stored and never leak data between tests.
  2. 2. At which level should you test that search ignores case?

    Test each behavior at the lowest level that can check it. A unit test is faster and pinpoints failures.
  3. 3. What is a good way to check that your tests really guard a behavior?

    Temporarily introducing a bug shows whether the suite would catch a real regression.
  4. 4. Why does each Ember test start from a fresh owner?

    Isolation keeps tests order-independent and reproducible.

Summary

  • Write the test plan first and place each behavior at the lowest sensible level.
  • Make dependencies replaceable (storage, clock, network) so tests control them.
  • Unit tests cover the service logic; rendering tests cover the editor's DOM behavior; one or two acceptance tests cover the main journey and a guard.
  • Check test quality by breaking the code on purpose.
  • Run the suite in CI so regressions never reach users.

Next: Ember Practice and Cheat Sheet