0
我有一個指令,注入的apiService是$ http和其他自定義服務的包裝。如何在指令測試中模擬服務?
,當我嘗試測試指令,我不知道如何嘲笑服務:
app.directive('coreMenu', ['apiService', function (apiService) {
return {
restrict : 'E',
replace : true,
templateUrl : 'Directives/CoreMenu.tpl.html',
link: function (scope) {
apiService.get({
module: 'Core',
route: 'Menu'
}).then(function (response) {
scope.menuItems = response.data;
}, function (response) {
// error: no menu available
});
}
};
}]);
測試:
describe('coreMenu directive', function() {
var $compile, $rootScope;
beforeEach(function() {
module('AdminTechPortal');
module('CoreLeftMenu.tpl.html');
inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
});
it('replaces the element with the appropriate content', function() {
var element = $compile("<core-menu></core-menu>")($rootScope);
$rootScope.$digest();
expect(element.html()).toContain('id="core-menu"');
});
});
該測試拋出(這是正常的):
Error: Unexpected request: GET /Core/Menu/
是否有可能使用$ httpbackend模擬apiService而不僅僅是xhr調用?
感謝您的解決方案 – CaptainMat