angularjasminevoidkarma-mocha

Test void with karma jasmine angular2


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.


Solution

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