I have a situation with a component that modifies the value of a signal declared within a service during its initialization. I've been attempting to test this behavior using Jest by spying on the set
method of the signal, but unfortunately, I haven't had any success so far.
Utilizing Angular 18.2.8 in conjunction with Jest 29.7.0.
Objective: To confirm that the component indeed sets the loading signal to true within its ngOnInit method.
service.ts
import { signal, Injectable } from '@angular/core';
@Injectable()
export class CardStateService {
loading = signal<boolean>(false);
}
component.ts
import { Component, OnInit, inject, ChangeDetectionStrategy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UntilDestroy } from '@ngneat/until-destroy';
import { CardStateService } from './card-state.service';
@UntilDestroy()
@Component({
selector: 'component-card',
templateUrl: './component.html',
styleUrls: ['./component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [CommonModule],
providers: [CardStateService],
})
export class Component implements OnInit {
stateService = inject(CardStateService);
ngOnInit(): void {
this.stateService.loading.set(true);
}
}
component.spec.ts
import { signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MockProvider } from 'ng-mocks';
import { CardStateService } from '../../shared/card-state.service';
import { Component } from './component';
describe('Component', () => {
let component: Component;
let fixture: ComponentFixture<Component>;
let cardStateServiceMock: CardStateService;
let mockStateService = {
loading: signal(false),
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [Component],
providers: [
MockProvider(CardStateService, mockStateService),
],
});
fixture = TestBed.createComponent(Component);
component = fixture.componentInstance;
cardStateServiceMock = TestBed.inject(CardStateService);
fixture.detectChanges();
});
it('should set loading to true when initializing component', () => {
const loadingSpy = jest.spyOn(mockStateService.loading, 'set')
component.ngOnInit();
expect(loadingSpy).toHaveBeenCalledWith(true);
});
});
Test result
Component› should set loading to true when initializing component
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: true
Number of calls: 0