Ember CLI Pretender Integration

4.0.0 · maintenance · verified Wed Apr 22

ember-cli-pretender is an Ember CLI addon designed to simplify the integration of the `pretender.js` HTTP mocking library into Ember applications. It abstracts away the manual import process of `pretender.js` files, making the `Pretender` constructor directly importable within the Ember app's testing environment. The current stable version is 4.0.0, which was released in 2020. While no longer under active, frequent development, it continues to serve its purpose for existing Ember projects. Key differentiators include its tight integration with the Ember CLI build pipeline, allowing developers to enable `pretender.js` conditionally (e.g., only for tests or also for production builds) and to opt out of polyfills like `fetch`. This addon is crucial for writing robust and isolated unit and integration tests that interact with network requests without relying on live backend services. Its release cadence has been infrequent, with the last major update several years ago, indicating a maintenance phase rather than active development.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install `ember-cli-pretender`, import `Pretender` in an Ember QUnit test, set up a mock server with `get` and `post` routes, and make `fetch` requests against it, then shut it down.

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

module('Unit | Utility | my-service', function(hooks) {
  setupTest(hooks);

  let server;

  hooks.beforeEach(function() {
    server = new Pretender(function() {
      this.get('/api/users', function() {
        return [200, { 'Content-Type': 'application/json' }, JSON.stringify([{ id: 1, name: 'Alice' }])];
      });
      this.post('/api/users', function(request) {
        const newUser = JSON.parse(request.requestBody);
        return [201, { 'Content-Type': 'application/json' }, JSON.stringify({ id: 2, name: newUser.name })];
      });
    });
  });

  hooks.afterEach(function() {
    server.shutdown();
  });

  test('it can fetch users', async function(assert) {
    const response = await fetch('/api/users');
    const data = await response.json();
    assert.deepEqual(data, [{ id: 1, name: 'Alice' }], 'should return mocked users');
  });

  test('it can create a user', async function(assert) {
    const response = await fetch('/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: 'Bob' })
    });
    const data = await response.json();
    assert.deepEqual(data, { id: 2, name: 'Bob' }, 'should return created user');
    assert.equal(response.status, 201, 'should return 201 status');
  });
});

view raw JSON →