我有一项具有以下功能的服务
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 进行存根,但我不明白应该返回什么存根以及如何从该服务调用该方法。