Friday, 15 July 2011

angularjs - How to mock service in angularAMD with karma/jasmine? -



angularjs - How to mock service in angularAMD with karma/jasmine? -

i have project using angularamd/requirejs/karma/jasmine, have basic configuration working, unit tests run , pass successfully.

i cannot mocked service injected correctly using either angular.mock.module or angularamd.value().

i have:

// service definition in services/myservice.js define(['app'], function(app) { app.factory('myservice', [ '$document', function($document) { function add(html) { $document.find('body').append(html); } homecoming { add: add together }; }]); } ); // test define(['angularamd', 'angular-mocks', 'app', 'services/myservice'], function(aamd, mocks, app) { describe('myservice', function() { var mybodymock = { append: function() {} }; var mydocumentmock = { find: function(sel) { // never gets called console.log('selector: ' + sel); homecoming mybodymock; } }; var svc; beforeeach(function() { // seek standard way mock service through ng-mock mocks.module(function($provide) { $provide.value('$document', mydocumentmock); }); // hedge bets - seek overriding in aamd ng-mock aamd.value('$document', mydocumentmock); }); beforeeach(function() { aamd.inject(['myservice', function(myservice) { svc = myservice; }]); }); it('should work', function() { // utilize svc expecting have injected mock of $document. spyon(mydocumentmock, 'find').andcallthrough(); spyon(mybodymock, 'append'); svc.add('<p></p>'); expect(mydocumentmock.find).tohavebeencalledwith('body'); expect(mybockmock.append).tohavebeencalledwith('<p></p>'); }); }); } );

does know i'm going wrong ? help much appreciated.

angular isn't asynchronous, think not ideia utilize both. if you're trying reach modularization method, okay, utilize requirejs optimizer build before set on browser, , tests, think can utilize requirejs optimizer build modules before, allow free "commonjs environment in tests".

angularjs karma-jasmine angular-amd

No comments:

Post a Comment