How to inject a mock service into another service in unit test

1,065 views
Skip to first unread message

Di Peng

unread,
Nov 5, 2012, 6:24:13 PM11/5/12
to ang...@googlegroups.com
Hi,
   I have created two services, A and B. B depends on A but I need to mock out A when unit testing B. How do I inject into B this mockA instead of the real A? Can someone point me to any code examples? 
Thank you very much
Di

Lee Byrd

unread,
Nov 6, 2012, 9:39:48 AM11/6/12
to ang...@googlegroups.com
+1

Peter Bacon Darwin

unread,
Nov 7, 2012, 5:53:00 AM11/7/12
to ang...@googlegroups.com
Either get hold of the original service A in your beforeEach and modify it or simply recreate it before your test runs.  Something like this:

angular.module('MockAModule', []).factory('A', function() {
 // Mock out A here
});

// This will load the BModule, and potential the original AModule if it is a dependency
beforeEach(module('BModule'));
// This will load the MockAModule, which will overwrite the original A service with your mock.
beforeEach(module('MockAModule'));

var B;
beforeEach(inject(B, function(_B_) {
 B = _B_;
});

describe('B', function() {
  // Test B
}

+1
--
You received this message because you are subscribed to the Google Groups "AngularJS" group.
To post to this group, send email to ang...@googlegroups.com.
To unsubscribe from this group, send email to angular+u...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular?hl=en.
 
 

Reply all
Reply to author
Forward
0 new messages