2

I'm trying to test my code with jasmine and karma.

When I test a method that returns a value it's ok. But my problem is how can I test a void method (that return nothing) for example this one:

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

With this function I check if an array of object `x contains an object or no.

If it is not the case I add it to the array. That's all.

I test it this way

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

  });

I got this error

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

Can anyone help me, please? I tried but I always get errors.

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
thouraya
  • 135
  • 2
  • 11
  • 1
    That function still has side-effects, it still *does* something. So *test the thing it does* - call it with an array and make sure the item gets added to it under the appropriate circumstances (and doesn't in the others). To put it another way: you must have had a reason to write that function, something you needed it to do: does it do that? Beyond that, please give a [mcve] of what you tried, what errors you get. – jonrsharpe Jul 02 '18 at 14:13
  • And without a [mcve], at least post the code you already tried, so that we have an idea of what is your issue. –  Jul 02 '18 at 14:14
  • jonrsharpe , trichetriche i updated it. Could you please take a look. Thanks – thouraya Jul 02 '18 at 14:43
  • You are simply spying on the method and expecting it to be called, But there is no code in between that will actually invoke the method. – Amit Chigadani Jul 02 '18 at 14:49
  • if i try to invoke this method by calling it like that : it('', () => { let component= new synthese(consoService); let x = [pHC,pHP]; let xx = [posteHC,posteHP]; component.concatenerSansDoublons(x,xx); spyOn(component,'aj'); expect(component.aj(x,pI)).toHaveBeenCalled(); }); that change nothing @AmitChigadani – thouraya Jul 02 '18 at 14:53

1 Answers1

1

Change your code like this:

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.
});
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • 1
    thaanks it works. But here: expect(x.indexOf(pI)).not.toBe(-1) you dont use really the spy or the component. It seems like you just test PI in an array x thats all. when you delete the sypAJ that will not change anything. – thouraya Jul 02 '18 at 15:50