Unit Tests

Test a Helper or Service in Isolation

Unit Tests

setupTest gives you an isolated container — look up a service or helper, exercise it, and assert with QUnit.

4 min read Level 2/5 #ember#testing#qunit
What you'll learn
  • Use setupTest from ember-qunit
  • Look up units via this.owner.lookup
  • Assert with QUnit assertions

Unit tests cover plain modules — services, helpers, utilities — with no DOM involved. They are the fastest layer and the simplest to write.

Anatomy

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

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

  test('adds an item', function (assert) {
    const cart = this.owner.lookup('service:cart');
    cart.add({ id: 1, name: 'Pen' });
    assert.strictEqual(cart.items.length, 1);
  });
});

setupTest(hooks) registers a fresh container before each test. Inside the test, this.owner is that container — use lookup to resolve any factory by full name (service:cart, helper:format-cents).

Stubbing Services

Override factories with register before lookup:

import Service from '@ember/service';

class StubAuth extends Service {
  currentUser = { id: 99 };
}

test('uses current user', function (assert) {
  this.owner.register('service:auth', StubAuth);
  const cart = this.owner.lookup('service:cart');
  assert.strictEqual(cart.ownerId, 99);
});

Async Tests

test('persists', async function (assert) {
  const cart = this.owner.lookup('service:cart');
  await cart.save();
  assert.true(cart.isSaved);
});

Mark the test function async and await. QUnit fails any test that throws or rejects.

Rendering Tests →