Ember Sinon

5.0.0 · active · verified Wed Apr 22

Ember Sinon is an Ember CLI addon that seamlessly integrates the Sinon.js testing framework into Ember applications, simplifying the process of creating test spies, stubs, and mocks. The current stable version is 5.0.0, which supports Ember.js v3.16+ and Sinon.js v9.0.0+. Historically, the addon has maintained a consistent release cadence, often aligning its major versions with significant Ember and Sinon updates several times a year. Key differentiators include its tight integration with the Ember CLI test suite, making Sinon globally available in test environments without manual configuration, and its direct compatibility with `ember install` workflows. It offloads the complexity of managing Sinon.js versions and ensuring it's properly hooked into Ember's testing infrastructure, providing a ready-to-use solution for behavior verification in unit and integration tests.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use Sinon spies and stubs within an Ember QUnit test to verify function calls and mock asynchronous operations.

import sinon from 'sinon';
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit'; // Assuming standard Ember QUnit setup

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

  test('doSomething() should run the callback passed with expected arguments', function(assert) {
    assert.expect(2); // QUnit assertion count
    let myService = this.owner.lookup('service:my-example-service'); // Assuming a service named 'my-example-service'

    // Create a spy to observe function calls
    let spy = sinon.spy();
    myService.doSomething(spy, 'test_argument');

    // Assert using Sinon's built-in assertion methods
    sinon.assert.calledOnce(spy);
    sinon.assert.calledWith(spy, 'test_argument');
  });

  test('fetchData() should return stubbed data without making an actual network request', async function(assert) {
    assert.expect(1);
    let myService = this.owner.lookup('service:my-example-service');

    // Create a stub for a method that might make an external call (e.g., fetch, AJAX)
    let stub = sinon.stub(myService, 'performNetworkRequest').returns(Promise.resolve({ id: 123, status: 'success' }));

    let result = await myService.fetchData();

    assert.deepEqual(result, { id: 123, status: 'success' }, 'should return the predefined stubbed data');

    // Restore the original method after the test to avoid side effects
    stub.restore();
  });
});

view raw JSON →