0
votes

Consider this method :

private subscriptions: Subscription = new Subscription();

private addFoo(): void {
    this.subscriptions.add(this.fooService.createFoo(fooObj).subscribe(
      (foo: Foo) => {
        if (foo) {
          // do something
           this.isCreated = true; // coverage show that the test doest not go inside this.
        }
      },
      (error: HttpErrorResponse) => {
        if (error) {
          // error handling
        }
      }
    ));
  }

And the test case using jasmine:

 it('should create foo successfully', () => {
    spyOn(fooService, 'createFoo').and.returnValue(of(foo));
    component.addFoo();
    expect(component.isCreated).toBeTruthy()
  })

Running test with coverage show that the line this.isCreated = true will not be executed.. Does someone have an idea why ?

1

1 Answers

0
votes

maybe it's an asynchronous operation? just try fakeAsync

you should surround your test suit function in fakeAsync and call flush before the actual assertion

   it('should create foo successfully', fakeAsync(() => {
      spyOn(fooService, 'createFoo').and.returnValue(of(foo));
      component.addFoo();

      flush(); // pop async queue

      expect(component.isCreated).toBeTruthy()
    }))

Or alternatively, you can use done function from jasmine. calling done be the last thing done by the asynchronous function or any of the functions that it calls

    it('should create foo successfully', function(done) {
      spyOn(fooService, 'createFoo').and.returnValue(of(foo));
      component.addFoo();

      expect(component.isCreated).toBeTruthy()
      done()
    });