이 사실을 알게 된 후 나는 내 자신의 질문에 대답 할 것이라고 생각했습니다. 위의 큰 실수는 angular.mock.module 대신 angular.module을 사용하는 것이 었습니다. 이는 angular-mock에 의해 모듈로 참조되는 편리함입니다. 그들은 전혀 같은 것이 아닙니다!
또한 테스트중인 모듈을 초기화하기 전에 먼저 모쥴 서비스를 angular.mock.module로 초기화하는 것으로 충분합니다. 위에 링크 된 질문에서 제안 된 것처럼 '모듈을 제 3의 모듈로 랩핑'할 필요가 없습니다. 재치에 : 종속성 모듈이 이미 존재
describe("Test Service", function() {
var TestService, getvaluestub;
beforeEach(function() {
// create mock service
var mock = {getvalue:function(){}}
angular.module('dependencymodule',[])
.service('dependencyservice',function() {
return mock;
});
//mock the function we are stubbing, (that, in this case, returns value 4)
getvaluestub = sinon.stub(mock,'getvalue')returns(4);
//instantiate your mock service
module('dependencymodule');
//instantiate the module of the service under test,
//that depends on 'dependencyservice' mocked above
//(ie - testmodule includes the service 'testservice')
module('testmodule');
//inject your test service for testing
inject(function ($injector) {
TestService = $injector.get('testservice');
})
//tests go here.....
경우 <가 인스턴스화>, 당신도 여전히 위의 모든 할 수있는, 또는 당신은 $ 인젝터에서 서비스를 획득하여 스파이와 스텁을 삽입 할 수 있으며, 테스트중인 서비스. 스파이/스텁은 < 전에 종속 서비스가 인스턴스화되기 전에 설정되어야합니다. 그렇지 않으면 종속 서비스가 인스턴스화됩니다. 모양은 다음과 같습니다.
describe("Test Service", function() {
var TestService, DependencyService, getvaluestub;
beforeEach(function() {
// these modules are specified in the application
module('dependencymodule');
module('testmodule');
inject(function ($injector) {
DependencyService = $injector.get('testservice');
getvaluestub = sinon.stub(DependencyService,'getvalue').returns(4);
OtherService = $injector.get('otherservice');
})
});
// test go here
그래서 여기에 있습니다. 바라건대 이것은 '모의 서비스로 모의 주사'를 찾는 사람에게 유용 할 것입니다.
고맙습니다. 다음은 서비스를 위해 스텁을 사용하여 서비스, 컨트롤러 및 필터를 테스트하는 또 다른 예제입니다. https://gist.github.com/clouddueling/11188718 –