Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Maybe you could create a custom wrapper mock around $httpBackend that handles your special needs.</p> <p>In detail, Angular overwrites components of the same name with a <strong>last-come first-served</strong> strategy, this means that the order you load your modules is important in your tests.</p> <p>When you define another service with the same name and load it after the first one, the last one will be injected instead of the first one. E.g.:</p> <pre><code>apptasticMock.service("socket", function($rootScope){ this.events = {}; // Receive Events this.on = function(eventName, callback){ if(!this.events[eventName]) this.events[eventName] = []; this.events[eventName].push(callback); } // Send Events this.emit = function(eventName, data, emitCallback){ if(this.events[eventName]){ angular.forEach(this.events[eventName], function(callback){ $rootScope.$apply(function() { callback(data); }); }); }; if(emitCallback) emitCallback(); } }); </code></pre> <p>This service offers the exact same interface and behaves exactly like the original one except it never communicates via any socket. This is the service we want to use for testing.</p> <p>With the load sequence of angular in mind, the tests then look like this:</p> <pre><code>describe("Socket Service", function(){ var socket; beforeEach(function(){ module('apptastic'); module('apptasticMock'); inject(function($injector) { socket = $injector.get('socket'); }); }); it("emits and receives messages", function(){ var testReceived = false; socket.on("test", function(data){ testReceived = true; }); socket.emit("test", { info: "test" }); expect(testReceived).toBe(true); }); </code></pre> <p>});</p> <p>The important thing here is that <code>module('apptasticMock')</code> gets executed after <code>module('apptastic')</code>. This overwrites the original socket implementation with the mocked one. The rest is just the normal dependency injection procedure.</p> <p><a href="http://southdesign.de/blog/mock-angular-js-modules-for-test-di.html" rel="nofollow">This article I wrote</a> could be interesting for you, as it goes into further details.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload