struggle to spyOn primeng's MessageService with jasmine

Discussão em 'Angular' iniciado por pirant, Março 25, 2025.

  1. pirant

    pirant Guest

    I'm new to unit testing with angular and I struggle a bit with testing adding new message with primeng's MessageService.
    Here is my component's code :

    @Component({
    selector: 'app-get-menu',
    templateUrl: './get-menu.component.html',
    styleUrls: ['./get-menu.component.scss'],
    providers: [MessageService],
    standalone: true,
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
    imports: [Toast],
    })
    export class GetMenuComponent implements OnInit {

    // Var
    menu: MenuInterface[] = [];

    // Constructor
    constructor(
    private apiService: ApiService,
    private router: Router,
    private dateTransformerService: DateTransformerService,
    private messageService: MessageService
    ) {}


    ngOnInit() {
    this.initData();
    }


    initData() {
    this.apiService.getMenu().subscribe({
    next: (menu) => {
    this.menu = menu;
    },
    error: (error) => {
    this.messageService.add({
    severity: "error",
    summary: "Error",
    detail: "Couldn't load menu",
    life: 10000,
    });
    }
    });
    }



    Here is my spec.ts code

    describe('GetMenuComponent', () => {

    let component: GetMenuComponent;
    let fixture: ComponentFixture<GetMenuComponent>;
    let apiService: ApiService;
    let messageService: MessageService;
    let router: Router;
    let dateTransformerService: DateTransformerService;


    beforeEach(() => {
    TestBed.configureTestingModule({
    imports: [GetMenuComponent],
    providers: [ApiService,MessageService, provideHttpClient(),
    provideHttpClientTesting(), Router, DateTransformerService]

    });
    fixture = TestBed.createComponent(GetMenuComponent);
    fixture.detectChanges();
    component = fixture.componentInstance;

    apiService = TestBed.inject(ApiService);
    router = TestBed.inject(Router);
    dateTransformerService = TestBed.inject(DateTransformerService);
    messageService = TestBed.inject(MessageService);
    });

    //already tried without the fakeAsync wrapper
    it("Should handle errors and show error message", fakeAsync(() => {

    spyOn(apiService, 'getMenu').and.returnValue(throwError(() => new Error("some error")));
    //already tried with spyOn(apiService, 'getMenu').and.throwError("some error");
    spyOn(messageService, 'add');
    component.initData();

    tick(200);
    expect(messageService.add).toHaveBeenCalled();
    }))



    The test always fail with the following error :


    Expected spy add to have been called.
    ​

    If I replace the messageService.add({...}) call to an other random function call in my component and try to test if this random function is being called, the test succeed.
    Am I missing something ?

    Thank you !

    Continue reading...

Compartilhe esta Página