首页 > 解决方案 > 用 karma jasmine angular2 测试 void

问题描述

我正在尝试用 jasmine 和 karma 测试我的代码。

当我测试一个返回值的方法时,没关系。但我的问题是如何测试一个 void 方法(什么都不返回),例如这个:

public aj(a: Array<x>, p: x) {
 if (a.indexOf(p) < 0) {
   a.push(p);
  }
 }

使用这个函数,我检查一个对象数组是否包含一个对象。

如果不是这种情况,我将其添加到数组中。就这样。

我这样测试

  it('', () => {
  let component= new synthese(consoService);
   let x = [pHC,pHP]
   spyOn(component,'aj');
   expect(component.aj(x,pI)).toHaveBeenCalled();

  });

我收到了这个错误

Error: <toHaveBeenCalled> : Expected a spy, but got undefined.
Usage: expect(<spyObj>).toHaveBeenCalled()

任何人都可以帮助我吗?我试过了,但总是出错。

标签: angularjasminevoidkarma-mocha

解决方案


像这样更改您的代码:

it('', () => {
  const component = new synthese(consoService);
  const x = [pHC, pHP]; // maybe you should check this, shouldn't it be let x = ['pHC','pHP']; ?

  component.aj(x, pI); // maybe you should check this, shouldn't it be component.aj(x, 'pI'); ?

  // check pI is in the array now since that's what the method does, push the element if it is not in the array
  expect(x).toContain(pl); // I used pI, but maybe check for 'pI' as my previous recommendations.
});

推荐阅读