2

I have the following scenario:

app.component.ts

isLoading = false;

someFunction(){
  this.isLoading = true;
  this.someService
      .someFuncInService
      .pipe(finalize(() => (this.isLoading = false)))
      .subscribe(data => {
         ...
      });
}

Now i want to test the isLoading variable, whether it is set false at the end or not.

How should i do it? fixture.detectChanges() isn't helping

1 Answers1

0

You need to do something like this:

In your component.spec.ts, add a mock service, and return a value so that this line of code gets covered

in component.spec.ts, before describe(); write this:

@Injectable()
class MockService extends SomeService {
  someFunctionService() {
    return of({your mock data})
  }
}

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [yourComponent], 
      *************** ADD THIS LINE *************
      providers: [
         {
           provide: SomeService,
           useClass: MockService
         }
      ]
    }).compileComponents();
}));


// Your test case

it('should run #someFunction() method', () => {
  component.isLoading = false;
  spyOn(component, 'someFunction').and.callThrough();
  component.someFunction();
  expect(component.someFunction).toHaveBeenCalled();
}) 

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Srikar Phani Kumar M
  • 1,069
  • 1
  • 3
  • 8