Testing Angular signal fails

Discussão em 'Angular' iniciado por Saeid Khodarahmi, Março 7, 2025.

  1. footer component ts file:


    import { AppSignalState } from './../../app-state/app-state.service';
    import { CommonModule } from '@angular/common';
    import {
    ChangeDetectionStrategy,
    Component,
    computed,
    inject,
    } from '@angular/core';
    import { RouterLink, RouterLinkActive } from '@angular/router';

    @Component({
    selector: 'app-footer',
    imports: [CommonModule, RouterLink, RouterLinkActive],
    templateUrl: './footer.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
    styles: [
    `
    .nav .nav-item .active_section {
    color: #257bb1;
    }
    `,
    ],
    })
    export class FooterComponent {
    currentYear = new Date();
    // signals
    appSignalState = inject(AppSignalState);
    serverBuildData = this.appSignalState.getStateServerBuildData();
    isUserAuthenticated = this.appSignalState.isUserLoggedIn();
    userMfaAuthRequired = this.appSignalState.userMfaAuthRequired();
    userResetPasswordRequired = this.appSignalState.userResetPasswordRequired();
    isContractAgreementRequired =
    this.appSignalState.isContractAgreementRequired();
    canShowLogin = computed(() => {
    return (
    !this.userMfaAuthRequired() &&
    !this.userResetPasswordRequired() &&
    !this.isContractAgreementRequired() &&
    !this.isUserAuthenticated()
    );
    });
    }

    test file is here:


    import { ComponentFixture, TestBed } from '@angular/core/testing';
    import { FooterComponent } from './footer.component';
    import { AppSignalState } from '../../app-state/app-state.service';
    import { signal, WritableSignal } from '@angular/core';
    import { provideRouter } from '@angular/router';

    describe('FooterComponent (Standalone)', () => {
    let component: FooterComponent;
    let fixture: ComponentFixture<FooterComponent>;
    let stateMock: jasmine.SpyObj<AppSignalState>;

    beforeEach(() => {
    const mockAppState = jasmine.createSpyObj('AppSignalState', [], {
    userMfaAuthRequired: signal(false) as WritableSignal<boolean>,
    userResetPasswordRequired: signal(false) as WritableSignal<boolean>,
    isContractAgreementRequired: signal(false) as WritableSignal<boolean>,
    isUserLoggedIn: signal(false) as WritableSignal<boolean>,
    getStateServerBuildData: signal({ version: '1.0.0' }) as WritableSignal<{
    version: string;
    }>,
    });

    TestBed.configureTestingModule({
    imports: [FooterComponent], // Import the standalone component
    providers: [
    provideRouter([]),
    {
    provide: AppSignalState,
    useValue: mockAppState,
    },
    ],
    }).compileComponents();

    fixture = TestBed.createComponent(FooterComponent);
    component = fixture.componentInstance;

    stateMock = TestBed.inject(
    AppSignalState
    ) as jasmine.SpyObj<AppSignalState>;
    });

    it('should create', () => {
    expect(component).toBeTruthy();
    });
    it('should use the mocked signal', () => {
    expect(stateMock.userMfaAuthRequired()).toBe(false);
    expect(stateMock.userResetPasswordRequired()).toBe(false);
    expect(stateMock.isContractAgreementRequired()).toBe(false);
    expect(stateMock.isUserLoggedIn()).toBe(false);
    });

    it('should initialize currentYear with the current year', () => {
    expect(component.currentYear.getFullYear()).toBe(new Date().getFullYear());
    });
    it('should get serverBuildData from AppSignalState', () => {
    const mockServerBuildData = { version: '1.0.0' };
    expect(stateMock.getStateServerBuildData()).toEqual(mockServerBuildData);
    });
    it('should return true if all conditions are false', () => {
    // stateMock.userMfaAuthRequired.and.returnValue(signal(false));
    // stateMock.isContractAgreementRequired.and.returnValue(signal(false));
    // stateMock.isUserLoggedIn.and.returnValue(signal(false));
    // fixture.detectChanges();

    expect(component.canShowLogin()).toBe(true);
    });
    });
    service :


    @Injectable({
    providedIn: 'root',
    })
    export class AppSignalState {
    private readonly stateSessionItem = 'state';
    private readonly state = signal<AppStateInterface>(appInitialState());
    private readonly encryptedState: boolean = false;
    private readonly JWT_TOKEN_WORD = 'Bearer_';
    private spinnerService = inject(NgxSpinnerService);
    mfaUtilityService = inject(MfaUtilityService);
    httpClient = inject(HttpClient);
    isUserLoggedIn(): Signal<boolean | unknown> {
    return computed(() => {
    return ...
    }
    userMfaAuthRequired(): Signal<boolean | unknown> {
    return computed(() => {
    return ....
    });
    }
    ....


    }

    I am getting error in the canShowLogin test case : TypeError: this.userMfaAuthRequired is not a function also how to change the values of the signals and test canShowLogin with different parameters. the stateMock.userMfaAuthRequired.and.returnValue(signal(false)); not working and giving error.

    thanks very much

    Continue reading...

Compartilhe esta Página