Search code examples
angularkarma-jasmineangular-test

Angular: Testing - Expected spy open to have been called


I'm writing a test for pop up modal. Its throwing an error Expected spy open to have been called and spy open already declared. May i know what I missed here?

app.spec.ts

      it('should open modal', () => {
        const translation = {
          statusMessage: {
            popup: {
              badRequest: {
                title: 'Bad Request',
                message: 'Message..'
              }
            }
          }
        };
        spyOn(translate, 'getTranslation').and.returnValue(of(translation));
        spyOn(modalService, 'open').and.callThrough();

        const title = translate.get('title');
        const message = translate.get('message');

        component.showPopUp('title', 'message');
        fixture.detectChanges();
        expect(modalService.open).toHaveBeenCalled();
      });

app.ts

  showModal(title, message) {
    this.translate.getTranslation('en').subscribe((translations) => {
      this.modalService.open(
        title,
        message,
        {
          title: 'Go back',
          onClick: () => {
            return;
          }
        },
        true
      );
    });
  }

Solution

  • You are testing an asynchronous code i suggest that you use fakeAsync, try this

    it('should work..', fakeAsync(() => {
       const translation = {
          statusMessage: {
            popup: {
              badRequest: {
                title: 'Bad Request',
                message: 'Message..'
              }
            }
          }
        };
        spyOn(translate, 'getTranslation').and.returnValue(of(translation));
        spyOn(modalService, 'open').and.callThrough();
    
        const title = translate.get('title');
        const message = translate.get('message');
    
        component.showPopUp('title', 'message');
        tick();
        fixture.detectChanges();
        expect(modalService.open).toHaveBeenCalled();
    }));