Home > front end >  Testing method calls within subscribe call back function
Testing method calls within subscribe call back function

Time:06-28

I'm trying to create a test which tests whether a method has been called within the subscribe call back function. This is the method in which the test has been setup for:

 save() {
   this.testService.upsert(this.test).subscribe(() => {
        this.testMethod();
   });
 }

This is the test I have setup:

 it('should call testMethod()', () => {
       mockTestService.upsert.and.returnValue(of(null));
       component.save();
       const spy = spyOn(component, 'testMethod');
       expect(spy.calls.count()).toBe(1);
 });

I have a spy object setup on the service:

beforeEach(() => {
        mockTestService = jasmine.createSpyObj(['upsert']);
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            declarations: [TestComponent],
            providers: [
                { provide: TestService, useValue: mockTestService },
            ],
            schemas: [NO_ERRORS_SCHEMA]
        })
            .compileComponents();
        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
    });

The test is failing with 'Error: Expected 0 to be 1'

Anyone know how to approach testing method calls within a subscribe call back?

CodePudding user response:

You're spying too late. Spy on testMethod before calling the component.save() method.

it('should call testMethod()', () => {
       mockTestService.upsert.and.returnValue(of(null));
       // !! spy here
       const spy = spyOn(component, 'testMethod');
       component.save();
       expect(spy.calls.count()).toBe(1);
 });
  • Related