Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Projects and Practice

Ember Practice and Cheat Sheet

Practice Ember concepts with runnable exercises on services, tracked state and testing, review common mistakes, and keep a one-page cheat sheet of the key APIs.

Reading about a framework only gets you so far; the ideas stick when you use them. This closing lesson gives you practice exercises for the second half of the course (services, tracked state, testing, building and deploying), a table of common mistakes with fixes, and a cheat sheet you can keep open while you work.

The exercises are runnable plain-JavaScript versions of the real Ember patterns, because the site cannot run the framework. Each one has a starter, a hint and a check. Try it yourself before reading the hint.

Exercise 1: a lazy service registry

Build the smallest dependency-injection container: register(name, Class) and lookup(name), where lookup creates the instance once. Hint: keep two maps, one of classes and one of instances.

JS Exercise 1: write register and lookup

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

No output.

A finished solution is in the editor; delete the body of lookup and write it again from memory to test yourself.

Exercise 2: spot the reactivity bug

This component never updates its list. Find the bug and fix it without changing the template. The model uses a TrackedField that, like @tracked, only notices assignment.

JS Exercise 2: fix the stale list

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

No output.

The cause is the second item in the checklist from Reactivity Pitfalls: the field was changed by mutation instead of assignment. You can also fix it by making the array a TrackedArray.

Exercise 3: a debounced search service

A search box should call the server only after the user pauses typing, and ignore stale responses. Write search(query) on this service. Hint: combine a timer id with a ticket number.

JS Exercise 3: debounce and ignore stale replies

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

No output.

Only one request goes out. In real Ember apps this is a classic use of ember-concurrency (a task with restartable and timeout), but the idea above is the same.

Exercise 4: write the missing test

Given a formatCount helper, write assertions for the cases that matter. Add at least two edge cases of your own; the runner tells you if any fail.

JS Exercise 4: cover the edge cases

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

No output.

Good tests find surprising behavior like this. Deciding what the right output is, and then pinning it down in a test, is half the value of testing.

More practice ideas

  1. Add a dark-mode toggle that is stored in a settings service and persisted.
  2. Build a toast component backed by the notifications service with auto-dismiss.
  3. Create an order form with derived validation (canSubmit) and test it at all three levels.
  4. Write a helper that formats file sizes (1536 becomes 1.5 KB) with a full table of tests.
  5. Write the deployment checklist for your own app: host, fallback rule, cache headers, environment values.
  6. Take the task board and add per-column filters using @cached getters.

Common mistakes

Mistake Symptom Fix
Forgetting @tracked screen never updates tracked on any displayed field that changes
push/index assignment on a plain array list does not change assign a new array or use TrackedArray
Method used as a callback without @action this is undefined add @action
Copying this.args.x into a field stale after the parent changes read the argument or use a getter
Setting tracked state in a getter backtracking re-render error derive instead, or move to an action
Giant app-state service everything depends on everything small focused services
Reading a service in a plain class error: no owner setOwner or pass dependencies in
Missing await in a test assertion runs too early await every helper
Real network in tests slow, flaky tests fake service or request interceptor
History URLs without a server fallback 404 on refresh serve index.html for non-file paths
Secrets in config/environment.js key visible in the browser keep secrets on a server
Long caching of index.html users stuck on an old release no-cache for the HTML

Cheat sheet

Services

JavaScript
import Service, { service } from '@ember/service';
export default class CartService extends Service {
  @service router;            // inject; name from file name
  @service('shopping-cart') cart; // explicit name
}
// this.owner.lookup('service:cart'), this.owner.register('service:cart', Fake)

Tracked state

JavaScript
import { tracked, cached } from '@glimmer/tracking';
import { TrackedArray, TrackedMap, TrackedSet, TrackedObject } from 'tracked-built-ins';

@tracked count = 0;            // noticed on assignment
get double() { return this.count * 2; }   // derived, always fresh
@cached get expensive() { /* memoized by tracked reads */ }
this.items = [...this.items, x];          // immutable update
items = new TrackedArray();               // or a tracked collection

Router service

JavaScript
this.router.transitionTo('posts.post', id);   // adds history
this.router.replaceWith('login');             // replaces history
this.router.currentRouteName; this.router.currentURL; this.router.isActive('posts');

Testing

JavaScript
setupTest(hooks);              // unit: this.owner
setupRenderingTest(hooks);     // component: render(), click(), fillIn()
setupApplicationTest(hooks);   // acceptance: visit(), currentURL()
assert.dom('[data-test-x]').hasText('...');
assert.step('called'); assert.verifySteps(['called']);
await settled();               // wait for pending work

Commands

Command Use
ember generate service name new service and test
ember serve development server on port 4200
ember test --filter "text" run matching tests
ember build --environment=production release build in dist/
ember install addon install an addon

Deploying: upload dist/; fallback to index.html; index.html is no-cache; hashed assets are immutable; assets first, HTML last.

Where to go next

You now have the whole picture: routes and templates, components, data, services, tracked state, tests and deployment. To keep growing:

  • Build something real and small, and deploy it.
  • Read the source of one popular addon to see how real code is organized.
  • Explore server-side rendering with FastBoot if your pages must be indexed by search engines.
  • Revisit the earlier chapters of this track as you build; many ideas make more sense the second time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A button handler method uses this.count but this is undefined when clicked. What fixes it?

    @action binds the method so this is the component when the browser calls it.
  2. 2. Which is the correct way to make a plain array in a tracked field show a new item?

    Assigning a new array is noticed by @tracked. The other lines mutate the existing array in place.
  3. 3. Which cache setting belongs to index.html in production?

    The HTML references the current hashed assets, so browsers must revalidate it to learn about new releases.
  4. 4. Where should a test replace the real session service with a fake?

    Registering before the first lookup means the code under test receives the fake through normal injection.

Summary

  • Practice each concept in small runnable pieces: a container, a reactivity fix, a debounced search, edge-case tests.
  • Most Ember bugs come from a short list: missing @tracked, mutation, missing @action, copied arguments, backtracking writes.
  • Keep the cheat sheet nearby for services, tracked state, the router service, test setups and commands.
  • Build and deploy a real project to cement the skills.

Next: Back to the Ember.js track