我有一个服务会抛出一个错误,我想对它进行单元测试,但不知何故我无法覆盖它,我确实设法为控制器做了这些:
describe('some test', function () {
var myService, exceptionHandler;
beforeEach(angular.mock.module('myModule', function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode("log");
}));
beforeEach(inject(function ($injector, $exceptionHandler) {
exceptionHandler = $exceptionHandler;
myService = $injector.get('myService');
}));
it('should throw an error', function () {
theService.somefunction('create an error');
expect(exceptionHandler.errors.length).toBe(1);
expect(exceptionHandler.errors[0].message).toBe('some text');
});
});
});
在某些功能中我只是这样做:
throw new Error('some text')
问题是该错误只是记录在Karma的控制台中,因此它似乎被重新引入而不是记录。 我该如何解决这个问题?
答案 0 :(得分:0)
建议在存根时使用sinon(虽然会显示两种方式):
describe('some test', function () {
var myService, exceptionHandler = {};
exceptionHandler.fn = function(exception, cause) {
throw exception;
};
beforeEach(module('myModule', function($provide) {
$provide.factory('$exceptionHandler', function(){
return function(exception, cause){
return exceptionHandler.fn(exception, cause);
};
});
}));
beforeEach(inject(function ($injector) {
myService = $injector.get('myService');
}));
it('should throw an error', function () {
var old = exceptionHandler.fn, caught = false, message = '';
exceptionHandler.fn = function(exception, cause) {
caught = true;
message = exception.message;
};
myService.somefunction('create an error');
expect(caught).toBe(true);
expect(message).toBe('message');
exceptionHandler.fn = old; //restore
// using sinon.js
sinon.stub(exceptionHandler, 'fn', function(exception){ });
myService.somefunction('create an error');
expect(exceptionHandler.fn.called).toBe(true);
expect(exceptionHandler.fn.getCall(0).args[0]).toMatch(/message/);
exceptionHandler.fn.restore();
});
});
sinon可以更容易地存根,并在完成后检查呼叫计数和恢复功能