在使用jasmine运行angular2单元测试时调用服务时出错

时间:2017-07-18 06:42:57

标签: angular unit-testing typescript karma-jasmine

我正在测试一个角度服务,我用打字稿编写代码但是当我运行我的测试用例时,我得到错误“this.someFunction.show()”不是函数,而是“这个。 someFunction.show()“在我的实际服务中。 这就是我想要做的。

myService.spec.ts

import { dep1, dep......m dep-n } from '../../../../some-modules';
describe('ServiceTest', () => {
let cashPaymentHandlerService : CashPaymentHandlerService;
it('for cash, when pick list enabled, 1 cash drawer, adds payment line', () => {
  methodOne(); //work fine
  methodTwo(false); //work fine
  methodThree(true); //work fine      
  methodFour(); //work fine
  methodFive(1); //work fine
  methodSix(); //work fine
  givenDependanciesAreMocked();
  whenHandlePaymentIsInvoked();
  expect(cashDrawerService.openCashDrawer).toHaveBeenCalled();
});

function givenDependanciesAreMocked(){
  TestBed.configureTestingModule({
 providers: [
   {provide: ServiceOne, useValue: serviceOne},
   {provide: ServiceTwo, useValue: serviceTwo},
   {provide: ServiceN, useValue: serviceN},
   CashPaymentHandlerService
 ]
});
cashPaymentHandlerService = TestBed.get(CashPaymentHandlerService);
}

function whenHandlePaymentIsInvoked() : any {
  cashPaymentHandlerService.handlePayment(cashPaymentRequest);
}

这是我的 cash-payment-handler.service.ts 文件

import { dep1, dep......m dep-n } from '../../../../some-modules';

export class CashPaymentHandlerService {
constructor(private service1 : Service1,
          private service2: Service2,
          private serviceN: ServiceN){
}

handlePayment(cashPaymentRequest: CashPaymentRequest) {
  let request = new service1();
  request.initialAmount = this.service2.dataModel.transactionDataModel.balance();
  request.onValueEntered = (response: AmountPromptResponse) => {
    if (!response.cancelled){
      this.addCashPaymentLine(response.value, cashPaymentRequest); // runs fine
    }
  };
  this.serviceN.show(request); //getting error on this line
}

}

来自 ServiceN.ts 的代码

constructor(
private someController: SomeController){
}

show(options?: NewRequest): void {
if (!options){
  options = new NewRequest();
}

this.someController.show(PromptComponent, options); // PromptComponent imported from some other component
}

我在许多论坛上搜索了解决方案,并花了一整天时间,但无法解决问题。任何帮助将受到高度赞赏。 Meherbani hosi nay。

1 个答案:

答案 0 :(得分:0)

已解决这个,我不得不为" this.serviceN.show(请求)添加模拟函数; "在我的" myService.spec.ts "文件和它工作正常,因为我试图测试的服务是调用一些其他组件,当单元测试调用它时,它无法在不同的服务中找到对其他方法的正确引用,因此它失败了。嘲笑那些依赖关系解决了我的问题。