これを理解した上で、自分の疑問に答えると思った。上の大きな間違いは、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 –