我已經具有以下功能
injectService(serviceToInject: string, methodToInvoke: string){
let service = this.$injector.get(serviceToInject);
service[methodToInvoke]();
}
我不知道我怎麼會測試這個服務?我試過這個:
(function() {
'use strict';
describe.only('ServiceA tests', function() {
let ServiceA;
beforeEach(angular.mock.module('main'));
beforeEach(inject(function (_ ServiceA_, _$injector_) {
ServiceA = _ServiceA_;
$injector = _$injector_;
}));
describe.only('injectServiceAndInvoke', function() {
it('given a string serviceToInject which is a valid service name and a string methodToInvoke which is valid method name without parameters, it should inject the service and call the method',() => {
let serviceName = 'validServiceName';
let methodWithoutParams = 'method';
let injectedService = $injector.get(serviceName);
// sandboxSinon.stub(ButtonService.$injector, 'get').withArgs(serviceName).returns(stubbedService);
let methodToBeCalled = sandboxSinon.stub(injectedService, methodWithoutParams).withArgs(undefined);
sandboxSinon.stub(ServiceA, 'tokenizeState').withArgs(methodWithoutParams).returns([methodWithoutParams, undefined]);
ServiceA.injectServiceAndInvoke(serviceName, methodWithoutParams);
expect(methodToBeCalled.calledOnce).to.equal(true);
});
});
});
})();
而我得到錯誤(正確),該服務'validServiceName'不存在。我也嘗試存根$ injector.get,但我不明白什麼應該返回這個存根,以及如何從這個服務調用該方法。
請提供更多的測試代碼,所以答案可能會考慮到它。 – estus
更新了測試 – geo
順便說一句,這感覺非常像服務定位器。爲什麼你需要這樣做,你是在測試你的實現還是你正在測試框架? –