用 karma jasmine angular2 测试 void

Test void with karma jasmine angular2

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

当我测试一个 return 值的方法时,没问题。但我的问题是如何测试一个无效方法(return 什么都没有)例如这个:

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

使用此函数,我检查对象 `x 的数组是否包含对象。

如果不是这样,我将其添加到数组中。就这些了。

我是这样测试的

  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()

有人能帮帮我吗?我试过了,但总是出错。

像这样更改您的代码:

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.
});