【问题标题】:Jasmine Expected jasmine.createSpyObj errorJasmine 预期的 jasmine.createSpyObj 错误
【发布时间】:2019-02-05 16:55:25
【问题描述】:

我正在尝试模拟并尝试满足以下方法的 else 条件,但由于 Expected spy modalService.open 没有被调用

而出现错误

这是组件代码

更新以下行后component.isError = true;

突出显示 If 块没有出现但错误仍然可用

public importDeals(upload, list) {
  this.fileName = '';
   let ngbModalOptions: NgbModalOptions = {
    backdrop : 'static',
    keyboard : false,
    windowClass: 'custom-class'
};   
if (!this.isError) {
  this.uploadModalRef = this.modalService.open(upload, ngbModalOptions);
}
this.tempContingency = list;
}

下面是当前的单元测试用例(Jasmine)

it('should import deals', () => {
  // component.importDeals;
  // expect(component.importDeals('upload','list')).toBeUndefined();
  component.importDeals;
  component.uploadModalRef = jasmine.createSpyObj('uploadModalRef', ['close']);
  let mockOptions: NgbModalOptions = {
    backdrop : 'static',
    keyboard : false,
    windowClass: 'custom-class'
  };
  const mockConfirm = 'confirm-template';
  component.importDeals(mockConfirm,'');
  expect(modalService.open).toHaveBeenCalledWith(mockConfirm, mockOptions);
});
it('should not import deals', () => { 
  component.importDeals; 
  component.modalService = jasmine.createSpyObj('modalService',['open'])
  const mockConfirm = 'confirm-template'; 

  component.importDeals(mockConfirm,''); 
  expect(modalService.open).not.toHaveBeenCalled(); 
  });

请让我知道我在这里做错了什么

【问题讨论】:

    标签: angular typescript jasmine karma-jasmine karma-coverage


    【解决方案1】:

    isError 的值设置为true,否则if 块将始终执行。

    it('should not import deals', () => { 
      component.importDeals; 
      component.modalService = jasmine.createSpyObj('modalService',['open']);
      component.isError = true; // <- this line
      const mockConfirm = 'confirm-template'; 
    
      component.importDeals(mockConfirm,''); 
      expect(modalService.open).not.toHaveBeenCalled(); 
    });
    

    【讨论】:

    • If 块现在可以了,但我仍然在控制台中收到错误,因为预期的间谍 modalService.open 没有被调用
    • 如果显示该错误,则表示正在调用该方法,这意味着该 if 块中的代码正在执行。确认的一个好方法是在 if 块中放置一个 console.log,以便确定它是否执行。
    猜你喜欢
    • 2017-07-08
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 2015-12-20
    • 2021-04-02
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多