diff --git a/src/app/features/registries/components/registries-metadata-step/registries-affiliated-institution/registries-affiliated-institution.component.spec.ts b/src/app/features/registries/components/registries-metadata-step/registries-affiliated-institution/registries-affiliated-institution.component.spec.ts index 385ae946b..40e29ec95 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-affiliated-institution/registries-affiliated-institution.component.spec.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-affiliated-institution/registries-affiliated-institution.component.spec.ts @@ -1,47 +1,55 @@ +import { Store } from '@ngxs/store'; + import { MockComponent } from 'ng-mocks'; +import { signal, WritableSignal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; import { AffiliatedInstitutionSelectComponent } from '@osf/shared/components/affiliated-institution-select/affiliated-institution-select.component'; -import { InstitutionsSelectors } from '@osf/shared/stores/institutions'; +import { ResourceType } from '@osf/shared/enums/resource-type.enum'; +import { Institution } from '@osf/shared/models/institutions/institutions.model'; +import { + FetchResourceInstitutions, + FetchUserInstitutions, + InstitutionsSelectors, + UpdateResourceInstitutions, +} from '@osf/shared/stores/institutions'; import { RegistriesAffiliatedInstitutionComponent } from './registries-affiliated-institution.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { MOCK_INSTITUTION } from '@testing/mocks/institution.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('RegistriesAffiliatedInstitutionComponent', () => { let component: RegistriesAffiliatedInstitutionComponent; let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; + let store: Store; + let resourceInstitutionsSignal: WritableSignal; - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build(); + beforeEach(() => { + resourceInstitutionsSignal = signal([]); - await TestBed.configureTestingModule({ - imports: [ - RegistriesAffiliatedInstitutionComponent, - OSFTestingModule, - MockComponent(AffiliatedInstitutionSelectComponent), - ], + TestBed.configureTestingModule({ + imports: [RegistriesAffiliatedInstitutionComponent, MockComponent(AffiliatedInstitutionSelectComponent)], providers: [ - { provide: ActivatedRoute, useValue: mockActivatedRoute }, + provideOSFCore(), provideMockStore({ signals: [ { selector: InstitutionsSelectors.getUserInstitutions, value: [] }, { selector: InstitutionsSelectors.areUserInstitutionsLoading, value: false }, - { selector: InstitutionsSelectors.getResourceInstitutions, value: [] }, + { selector: InstitutionsSelectors.getResourceInstitutions, value: resourceInstitutionsSignal }, { selector: InstitutionsSelectors.areResourceInstitutionsLoading, value: false }, { selector: InstitutionsSelectors.areResourceInstitutionsSubmitting, value: false }, ], }), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(RegistriesAffiliatedInstitutionComponent); component = fixture.componentInstance; + fixture.componentRef.setInput('draftId', 'draft-1'); fixture.detectChanges(); }); @@ -49,27 +57,26 @@ describe('RegistriesAffiliatedInstitutionComponent', () => { expect(component).toBeTruthy(); }); - it('should dispatch updateResourceInstitutions on selection', () => { - const actionsMock = { - updateResourceInstitutions: jest.fn(), - fetchUserInstitutions: jest.fn(), - fetchResourceInstitutions: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - const selected = [{ id: 'i2' }] as any; - component.institutionsSelected(selected); - expect(actionsMock.updateResourceInstitutions).toHaveBeenCalledWith('draft-1', 8, selected); + it('should dispatch fetchUserInstitutions and fetchResourceInstitutions on init', () => { + expect(store.dispatch).toHaveBeenCalledWith(new FetchUserInstitutions()); + expect(store.dispatch).toHaveBeenCalledWith( + new FetchResourceInstitutions('draft-1', ResourceType.DraftRegistration) + ); }); - it('should fetch user and resource institutions on init', () => { - const actionsMock = { - updateResourceInstitutions: jest.fn(), - fetchUserInstitutions: jest.fn(), - fetchResourceInstitutions: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - component.ngOnInit(); - expect(actionsMock.fetchUserInstitutions).toHaveBeenCalled(); - expect(actionsMock.fetchResourceInstitutions).toHaveBeenCalledWith('draft-1', 8); + it('should sync selectedInstitutions when resourceInstitutions emits', () => { + const institutions: Institution[] = [MOCK_INSTITUTION as Institution]; + resourceInstitutionsSignal.set(institutions); + fixture.detectChanges(); + expect(component.selectedInstitutions()).toEqual(institutions); + }); + + it('should dispatch updateResourceInstitutions on selection', () => { + (store.dispatch as jest.Mock).mockClear(); + const selected: Institution[] = [MOCK_INSTITUTION as Institution]; + component.institutionsSelected(selected); + expect(store.dispatch).toHaveBeenCalledWith( + new UpdateResourceInstitutions('draft-1', ResourceType.DraftRegistration, selected) + ); }); }); diff --git a/src/app/features/registries/components/registries-metadata-step/registries-affiliated-institution/registries-affiliated-institution.component.ts b/src/app/features/registries/components/registries-metadata-step/registries-affiliated-institution/registries-affiliated-institution.component.ts index 5fa7e1306..a16d71d2d 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-affiliated-institution/registries-affiliated-institution.component.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-affiliated-institution/registries-affiliated-institution.component.ts @@ -4,8 +4,7 @@ import { TranslatePipe } from '@ngx-translate/core'; import { Card } from 'primeng/card'; -import { ChangeDetectionStrategy, Component, effect, inject, OnInit, signal } from '@angular/core'; -import { ActivatedRoute } from '@angular/router'; +import { ChangeDetectionStrategy, Component, effect, input, OnInit, signal } from '@angular/core'; import { AffiliatedInstitutionSelectComponent } from '@osf/shared/components/affiliated-institution-select/affiliated-institution-select.component'; import { ResourceType } from '@osf/shared/enums/resource-type.enum'; @@ -25,8 +24,7 @@ import { changeDetection: ChangeDetectionStrategy.OnPush, }) export class RegistriesAffiliatedInstitutionComponent implements OnInit { - private readonly route = inject(ActivatedRoute); - private readonly draftId = this.route.snapshot.params['id']; + draftId = input.required(); selectedInstitutions = signal([]); @@ -53,10 +51,10 @@ export class RegistriesAffiliatedInstitutionComponent implements OnInit { ngOnInit() { this.actions.fetchUserInstitutions(); - this.actions.fetchResourceInstitutions(this.draftId, ResourceType.DraftRegistration); + this.actions.fetchResourceInstitutions(this.draftId(), ResourceType.DraftRegistration); } institutionsSelected(institutions: Institution[]) { - this.actions.updateResourceInstitutions(this.draftId, ResourceType.DraftRegistration, institutions); + this.actions.updateResourceInstitutions(this.draftId(), ResourceType.DraftRegistration, institutions); } } diff --git a/src/app/features/registries/components/registries-metadata-step/registries-contributors/registries-contributors.component.spec.ts b/src/app/features/registries/components/registries-metadata-step/registries-contributors/registries-contributors.component.spec.ts index 1ee6a31b7..aecb80277 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-contributors/registries-contributors.component.spec.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-contributors/registries-contributors.component.spec.ts @@ -1,40 +1,59 @@ +import { Store } from '@ngxs/store'; + import { MockComponent, MockProvider } from 'ng-mocks'; -import { of } from 'rxjs'; +import { Subject } from 'rxjs'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormControl } from '@angular/forms'; -import { ActivatedRoute } from '@angular/router'; import { UserSelectors } from '@core/store/user'; +import { AddContributorType } from '@osf/shared/enums/contributors/add-contributor-type.enum'; import { ResourceType } from '@osf/shared/enums/resource-type.enum'; import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { CustomDialogService } from '@osf/shared/services/custom-dialog.service'; import { ToastService } from '@osf/shared/services/toast.service'; -import { ContributorsSelectors } from '@osf/shared/stores/contributors/contributors.selectors'; +import { + BulkAddContributors, + BulkUpdateContributors, + ContributorsSelectors, + DeleteContributor, + GetAllContributors, + LoadMoreContributors, + ResetContributorsState, +} from '@osf/shared/stores/contributors'; import { ContributorsTableComponent } from '@shared/components/contributors/contributors-table/contributors-table.component'; +import { ContributorModel } from '@shared/models/contributors/contributor.model'; +import { ContributorDialogAddModel } from '@shared/models/contributors/contributor-dialog-add.model'; import { RegistriesContributorsComponent } from './registries-contributors.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { CustomConfirmationServiceMockBuilder } from '@testing/providers/custom-confirmation-provider.mock'; -import { CustomDialogServiceMockBuilder } from '@testing/providers/custom-dialog-provider.mock'; -import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { + MOCK_CONTRIBUTOR, + MOCK_CONTRIBUTOR_ADD, + MOCK_CONTRIBUTOR_WITHOUT_HISTORY, +} from '@testing/mocks/contributors.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; +import { + CustomConfirmationServiceMockBuilder, + CustomConfirmationServiceMockType, +} from '@testing/providers/custom-confirmation-provider.mock'; +import { + CustomDialogServiceMockBuilder, + CustomDialogServiceMockType, +} from '@testing/providers/custom-dialog-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; -import { ToastServiceMockBuilder } from '@testing/providers/toast-provider.mock'; +import { ToastServiceMockBuilder, ToastServiceMockType } from '@testing/providers/toast-provider.mock'; describe('RegistriesContributorsComponent', () => { let component: RegistriesContributorsComponent; let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; - let mockCustomDialogService: ReturnType; - let mockCustomConfirmationService: ReturnType; - let mockToast: ReturnType; + let store: Store; + let mockCustomDialogService: CustomDialogServiceMockType; + let mockCustomConfirmationService: CustomConfirmationServiceMockType; + let mockToast: ToastServiceMockType; - const initialContributors = [ - { id: '1', userId: 'u1', fullName: 'A', permission: 2 }, - { id: '2', userId: 'u2', fullName: 'B', permission: 1 }, - ] as any[]; + const initialContributors: ContributorModel[] = [MOCK_CONTRIBUTOR, MOCK_CONTRIBUTOR_WITHOUT_HISTORY]; beforeAll(() => { if (typeof (globalThis as any).structuredClone !== 'function') { @@ -46,88 +65,157 @@ describe('RegistriesContributorsComponent', () => { } }); - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build(); + beforeEach(() => { mockCustomDialogService = CustomDialogServiceMockBuilder.create().withDefaultOpen().build(); mockCustomConfirmationService = CustomConfirmationServiceMockBuilder.create().build(); mockToast = ToastServiceMockBuilder.create().build(); - await TestBed.configureTestingModule({ - imports: [RegistriesContributorsComponent, OSFTestingModule, MockComponent(ContributorsTableComponent)], + TestBed.configureTestingModule({ + imports: [RegistriesContributorsComponent, MockComponent(ContributorsTableComponent)], providers: [ - MockProvider(ActivatedRoute, mockActivatedRoute), + provideOSFCore(), MockProvider(CustomDialogService, mockCustomDialogService), MockProvider(CustomConfirmationService, mockCustomConfirmationService), MockProvider(ToastService, mockToast), provideMockStore({ signals: [ - { selector: UserSelectors.getCurrentUser, value: { id: 'u1' } }, + { selector: UserSelectors.getCurrentUser, value: { id: MOCK_CONTRIBUTOR.userId } }, { selector: ContributorsSelectors.getContributors, value: initialContributors }, { selector: ContributorsSelectors.isContributorsLoading, value: false }, + { selector: ContributorsSelectors.getContributorsTotalCount, value: 2 }, + { selector: ContributorsSelectors.isContributorsLoadingMore, value: false }, + { selector: ContributorsSelectors.getContributorsPageSize, value: 10 }, ], }), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(RegistriesContributorsComponent); component = fixture.componentInstance; fixture.componentRef.setInput('control', new FormControl([])); - const mockActions = { - getContributors: jest.fn().mockReturnValue(of({})), - updateContributor: jest.fn().mockReturnValue(of({})), - addContributor: jest.fn().mockReturnValue(of({})), - deleteContributor: jest.fn().mockReturnValue(of({})), - bulkUpdateContributors: jest.fn().mockReturnValue(of({})), - bulkAddContributors: jest.fn().mockReturnValue(of({})), - resetContributorsState: jest.fn().mockRejectedValue(of({})), - } as any; - Object.defineProperty(component, 'actions', { value: mockActions }); + fixture.componentRef.setInput('draftId', 'draft-1'); fixture.detectChanges(); }); - it('should request contributors on init', () => { - const actions = (component as any).actions; - expect(actions.getContributors).toHaveBeenCalledWith('draft-1', ResourceType.DraftRegistration); + it('should create', () => { + expect(component).toBeTruthy(); + }); + + it('should dispatch getContributors on init', () => { + expect(store.dispatch).toHaveBeenCalledWith(new GetAllContributors('draft-1', ResourceType.DraftRegistration)); }); it('should cancel changes and reset local contributors', () => { - (component as any).contributors.set([{ id: '3' }]); + component.contributors.set([{ ...MOCK_CONTRIBUTOR, id: 'changed' }]); component.cancel(); expect(component.contributors()).toEqual(JSON.parse(JSON.stringify(initialContributors))); }); it('should save changed contributors and show success toast', () => { - (component as any).contributors.set([{ ...initialContributors[0] }, { ...initialContributors[1], permission: 2 }]); + const changedContributor = { ...MOCK_CONTRIBUTOR_WITHOUT_HISTORY, permission: MOCK_CONTRIBUTOR.permission }; + component.contributors.set([{ ...MOCK_CONTRIBUTOR }, changedContributor]); + (store.dispatch as jest.Mock).mockClear(); component.save(); - expect(mockToast.showSuccess).toHaveBeenCalled(); + expect(store.dispatch).toHaveBeenCalledWith( + new BulkUpdateContributors('draft-1', ResourceType.DraftRegistration, [changedContributor]) + ); + expect(mockToast.showSuccess).toHaveBeenCalledWith( + 'project.contributors.toastMessages.multipleUpdateSuccessMessage' + ); + }); + + it('should bulk add registered contributors and show toast when add dialog closes', () => { + const dialogClose$ = new Subject(); + mockCustomDialogService.open.mockReturnValue({ onClose: dialogClose$, close: jest.fn() } as any); + (store.dispatch as jest.Mock).mockClear(); + + component.openAddContributorDialog(); + dialogClose$.next({ type: AddContributorType.Registered, data: [MOCK_CONTRIBUTOR_ADD] }); + + expect(store.dispatch).toHaveBeenCalledWith( + new BulkAddContributors('draft-1', ResourceType.DraftRegistration, [MOCK_CONTRIBUTOR_ADD]) + ); + expect(mockToast.showSuccess).toHaveBeenCalledWith('project.contributors.toastMessages.multipleAddSuccessMessage'); }); - it('should open add contributor dialog', () => { + it('should switch to unregistered dialog when add dialog closes with unregistered type', () => { + const dialogClose$ = new Subject(); + mockCustomDialogService.open.mockReturnValue({ onClose: dialogClose$, close: jest.fn() } as any); + const spy = jest.spyOn(component, 'openAddUnregisteredContributorDialog').mockImplementation(() => {}); + component.openAddContributorDialog(); - expect(mockCustomDialogService.open).toHaveBeenCalled(); + dialogClose$.next({ type: AddContributorType.Unregistered, data: [] }); + + expect(spy).toHaveBeenCalled(); }); - it('should open add unregistered contributor dialog', () => { + it('should bulk add unregistered contributor and show toast with name param', () => { + const dialogClose$ = new Subject(); + const unregisteredAdd = { ...MOCK_CONTRIBUTOR_ADD, fullName: 'Test User' }; + mockCustomDialogService.open.mockReturnValue({ onClose: dialogClose$, close: jest.fn() } as any); + (store.dispatch as jest.Mock).mockClear(); + component.openAddUnregisteredContributorDialog(); - expect(mockCustomDialogService.open).toHaveBeenCalled(); + dialogClose$.next({ type: AddContributorType.Unregistered, data: [unregisteredAdd] }); + + expect(store.dispatch).toHaveBeenCalledWith( + new BulkAddContributors('draft-1', ResourceType.DraftRegistration, [unregisteredAdd]) + ); + expect(mockToast.showSuccess).toHaveBeenCalledWith('project.contributors.toastMessages.addSuccessMessage', { + name: 'Test User', + }); + }); + + it('should switch to registered dialog when unregistered dialog closes with registered type', () => { + const dialogClose$ = new Subject(); + mockCustomDialogService.open.mockReturnValue({ onClose: dialogClose$, close: jest.fn() } as any); + const spy = jest.spyOn(component, 'openAddContributorDialog').mockImplementation(() => {}); + + component.openAddUnregisteredContributorDialog(); + dialogClose$.next({ type: AddContributorType.Registered, data: [] }); + + expect(spy).toHaveBeenCalled(); }); it('should remove contributor after confirmation and show success toast', () => { - const contributor = { id: '2', userId: 'u2', fullName: 'B' } as any; - component.removeContributor(contributor); + (store.dispatch as jest.Mock).mockClear(); + component.removeContributor(MOCK_CONTRIBUTOR_WITHOUT_HISTORY); expect(mockCustomConfirmationService.confirmDelete).toHaveBeenCalled(); - const call = (mockCustomConfirmationService.confirmDelete as any).mock.calls[0][0]; + const call = (mockCustomConfirmationService.confirmDelete as jest.Mock).mock.calls[0][0]; call.onConfirm(); - expect(mockToast.showSuccess).toHaveBeenCalled(); + expect(store.dispatch).toHaveBeenCalledWith( + new DeleteContributor('draft-1', ResourceType.DraftRegistration, MOCK_CONTRIBUTOR_WITHOUT_HISTORY.userId) + ); + expect(mockToast.showSuccess).toHaveBeenCalledWith('project.contributors.removeDialog.successMessage', { + name: MOCK_CONTRIBUTOR_WITHOUT_HISTORY.fullName, + }); + }); + + it('should return true for hasChanges when contributors differ from initial', () => { + component.contributors.set([{ ...MOCK_CONTRIBUTOR, id: 'changed' }]); + expect(component.hasChanges).toBe(true); + }); + + it('should return false for hasChanges when contributors match initial', () => { + expect(component.hasChanges).toBe(false); + }); + + it('should dispatch resetContributorsState on destroy', () => { + (store.dispatch as jest.Mock).mockClear(); + component.ngOnDestroy(); + expect(store.dispatch).toHaveBeenCalledWith(new ResetContributorsState()); + }); + + it('should dispatch loadMoreContributors', () => { + (store.dispatch as jest.Mock).mockClear(); + component.loadMoreContributors(); + expect(store.dispatch).toHaveBeenCalledWith(new LoadMoreContributors('draft-1', ResourceType.DraftRegistration)); }); it('should mark control touched and dirty on focus out', () => { - const control = new FormControl([]); - const spy = jest.spyOn(control, 'updateValueAndValidity'); - fixture.componentRef.setInput('control', control); component.onFocusOut(); - expect(control.touched).toBe(true); - expect(control.dirty).toBe(true); - expect(spy).toHaveBeenCalled(); + expect(component.control().touched).toBe(true); + expect(component.control().dirty).toBe(true); }); }); diff --git a/src/app/features/registries/components/registries-metadata-step/registries-contributors/registries-contributors.component.ts b/src/app/features/registries/components/registries-metadata-step/registries-contributors/registries-contributors.component.ts index c69bc4e41..af89f0281 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-contributors/registries-contributors.component.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-contributors/registries-contributors.component.ts @@ -4,9 +4,8 @@ import { TranslatePipe } from '@ngx-translate/core'; import { Button } from 'primeng/button'; import { Card } from 'primeng/card'; -import { TableModule } from 'primeng/table'; -import { filter, map, of } from 'rxjs'; +import { EMPTY, filter, switchMap, tap } from 'rxjs'; import { ChangeDetectionStrategy, @@ -20,9 +19,8 @@ import { OnInit, signal, } from '@angular/core'; -import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; -import { FormControl, FormsModule } from '@angular/forms'; -import { ActivatedRoute } from '@angular/router'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { FormControl } from '@angular/forms'; import { AddContributorDialogComponent, @@ -51,21 +49,19 @@ import { TableParameters } from '@shared/models/table-parameters.model'; @Component({ selector: 'osf-registries-contributors', - imports: [FormsModule, TableModule, ContributorsTableComponent, TranslatePipe, Card, Button], + imports: [ContributorsTableComponent, TranslatePipe, Card, Button], templateUrl: './registries-contributors.component.html', styleUrl: './registries-contributors.component.scss', changeDetection: ChangeDetectionStrategy.OnPush, }) export class RegistriesContributorsComponent implements OnInit, OnDestroy { control = input.required(); + draftId = input.required(); - readonly destroyRef = inject(DestroyRef); - readonly customDialogService = inject(CustomDialogService); - readonly toastService = inject(ToastService); - readonly customConfirmationService = inject(CustomConfirmationService); - - private readonly route = inject(ActivatedRoute); - private readonly draftId = toSignal(this.route.params.pipe(map((params) => params['id'])) ?? of(undefined)); + private readonly destroyRef = inject(DestroyRef); + private readonly customDialogService = inject(CustomDialogService); + private readonly toastService = inject(ToastService); + private readonly customConfirmationService = inject(CustomConfirmationService); initialContributors = select(ContributorsSelectors.getContributors); contributors = signal([]); @@ -112,11 +108,10 @@ export class RegistriesContributorsComponent implements OnInit, OnDestroy { } onFocusOut() { - if (this.control()) { - this.control().markAsTouched(); - this.control().markAsDirty(); - this.control().updateValueAndValidity(); - } + const control = this.control(); + control.markAsTouched(); + control.markAsDirty(); + control.updateValueAndValidity(); } cancel() { @@ -142,20 +137,21 @@ export class RegistriesContributorsComponent implements OnInit, OnDestroy { }) .onClose.pipe( filter((res: ContributorDialogAddModel) => !!res), - takeUntilDestroyed(this.destroyRef) - ) - .subscribe((res: ContributorDialogAddModel) => { - if (res.type === AddContributorType.Unregistered) { - this.openAddUnregisteredContributorDialog(); - } else { - this.actions + switchMap((res: ContributorDialogAddModel) => { + if (res.type === AddContributorType.Unregistered) { + this.openAddUnregisteredContributorDialog(); + return EMPTY; + } + + return this.actions .bulkAddContributors(this.draftId(), ResourceType.DraftRegistration, res.data) - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe(() => - this.toastService.showSuccess('project.contributors.toastMessages.multipleAddSuccessMessage') + .pipe( + tap(() => this.toastService.showSuccess('project.contributors.toastMessages.multipleAddSuccessMessage')) ); - } - }); + }), + takeUntilDestroyed(this.destroyRef) + ) + .subscribe(); } openAddUnregisteredContributorDialog() { @@ -166,19 +162,22 @@ export class RegistriesContributorsComponent implements OnInit, OnDestroy { }) .onClose.pipe( filter((res: ContributorDialogAddModel) => !!res), + switchMap((res) => { + if (res.type === AddContributorType.Registered) { + this.openAddContributorDialog(); + return EMPTY; + } + + const params = { name: res.data[0].fullName }; + return this.actions + .bulkAddContributors(this.draftId(), ResourceType.DraftRegistration, res.data) + .pipe( + tap(() => this.toastService.showSuccess('project.contributors.toastMessages.addSuccessMessage', params)) + ); + }), takeUntilDestroyed(this.destroyRef) ) - .subscribe((res: ContributorDialogAddModel) => { - if (res.type === AddContributorType.Registered) { - this.openAddContributorDialog(); - } else { - const params = { name: res.data[0].fullName }; - - this.actions.bulkAddContributors(this.draftId(), ResourceType.DraftRegistration, res.data).subscribe({ - next: () => this.toastService.showSuccess('project.contributors.toastMessages.addSuccessMessage', params), - }); - } - }); + .subscribe(); } removeContributor(contributor: ContributorModel) { diff --git a/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.scss b/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.scss index 7f863186d..e69de29bb 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.scss +++ b/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.scss @@ -1,4 +0,0 @@ -.highlight-block { - padding: 0.5rem; - background-color: var(--bg-blue-2); -} diff --git a/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.spec.ts b/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.spec.ts index bd5a86de0..18a8e69c4 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.spec.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.spec.ts @@ -1,48 +1,57 @@ +import { Store } from '@ngxs/store'; + import { MockComponent } from 'ng-mocks'; +import { signal, WritableSignal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormControl, FormGroup } from '@angular/forms'; -import { ActivatedRoute } from '@angular/router'; -import { RegistriesSelectors } from '@osf/features/registries/store'; +import { FetchLicenses, RegistriesSelectors, SaveLicense } from '@osf/features/registries/store'; import { LicenseComponent } from '@osf/shared/components/license/license.component'; +import { LicenseModel } from '@shared/models/license/license.model'; import { RegistriesLicenseComponent } from './registries-license.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('RegistriesLicenseComponent', () => { let component: RegistriesLicenseComponent; let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; + let store: Store; + let licensesSignal: WritableSignal; + let selectedLicenseSignal: WritableSignal<{ id: string; options?: Record } | null>; + let draftRegistrationSignal: WritableSignal | null>; + + const mockLicense: LicenseModel = { id: 'lic-1', name: 'MIT', requiredFields: [], url: '', text: '' }; + const mockDefaultLicense: LicenseModel = { id: 'default-1', name: 'Default', requiredFields: [], url: '', text: '' }; - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build(); + beforeEach(() => { + licensesSignal = signal([]); + selectedLicenseSignal = signal<{ id: string; options?: Record } | null>(null); + draftRegistrationSignal = signal | null>({ + providerId: 'osf', + }); - await TestBed.configureTestingModule({ - imports: [RegistriesLicenseComponent, OSFTestingModule, MockComponent(LicenseComponent)], + TestBed.configureTestingModule({ + imports: [RegistriesLicenseComponent, MockComponent(LicenseComponent)], providers: [ - { provide: ActivatedRoute, useValue: mockActivatedRoute }, + provideOSFCore(), provideMockStore({ signals: [ - { selector: RegistriesSelectors.getLicenses, value: [] }, - { selector: RegistriesSelectors.getSelectedLicense, value: null }, - { selector: RegistriesSelectors.getDraftRegistration, value: { providerId: 'osf' } }, + { selector: RegistriesSelectors.getLicenses, value: licensesSignal }, + { selector: RegistriesSelectors.getSelectedLicense, value: selectedLicenseSignal }, + { selector: RegistriesSelectors.getDraftRegistration, value: draftRegistrationSignal }, ], }), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(RegistriesLicenseComponent); component = fixture.componentInstance; fixture.componentRef.setInput('control', new FormGroup({ id: new FormControl('') })); - const mockActions = { - fetchLicenses: jest.fn().mockReturnValue({}), - saveLicense: jest.fn().mockReturnValue({}), - } as any; - Object.defineProperty(component, 'actions', { value: mockActions }); + fixture.componentRef.setInput('draftId', 'draft-1'); fixture.detectChanges(); }); @@ -50,36 +59,90 @@ describe('RegistriesLicenseComponent', () => { expect(component).toBeTruthy(); }); - it('should fetch licenses on init when draft present', () => { - expect((component as any).actions.fetchLicenses).toHaveBeenCalledWith('osf'); + it('should dispatch fetchLicenses on init when draft present', () => { + expect(store.dispatch).toHaveBeenCalledWith(new FetchLicenses('osf')); + }); + + it('should fetch licenses only once even if draft re-emits', () => { + (store.dispatch as jest.Mock).mockClear(); + draftRegistrationSignal.set({ providerId: 'other' }); + fixture.detectChanges(); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchLicenses)); + }); + + it('should sync selected license to control when license exists in list', () => { + licensesSignal.set([mockLicense]); + selectedLicenseSignal.set({ id: 'lic-1' }); + fixture.detectChanges(); + expect(component.control().get('id')?.value).toBe('lic-1'); + }); + + it('should apply default license and save when no selected license', () => { + (store.dispatch as jest.Mock).mockClear(); + draftRegistrationSignal.set({ providerId: 'osf', defaultLicenseId: 'default-1' }); + licensesSignal.set([mockDefaultLicense]); + fixture.detectChanges(); + expect(component.control().get('id')?.value).toBe('default-1'); + expect(store.dispatch).toHaveBeenCalledWith(new SaveLicense('draft-1', 'default-1')); + }); + + it('should apply default license but not save when it has required fields', () => { + (store.dispatch as jest.Mock).mockClear(); + const licenseWithFields: LicenseModel = { + id: 'default-2', + name: 'CC-BY', + requiredFields: ['year'], + url: '', + text: '', + }; + draftRegistrationSignal.set({ providerId: 'osf', defaultLicenseId: 'default-2' }); + licensesSignal.set([licenseWithFields]); + fixture.detectChanges(); + expect(component.control().get('id')?.value).toBe('default-2'); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(SaveLicense)); + }); + + it('should prefer selected license over default license', () => { + licensesSignal.set([mockDefaultLicense, mockLicense]); + draftRegistrationSignal.set({ providerId: 'osf', defaultLicenseId: 'default-1' }); + selectedLicenseSignal.set({ id: 'lic-1' }); + fixture.detectChanges(); + expect(component.control().get('id')?.value).toBe('lic-1'); }); it('should set control id and save license when selecting simple license', () => { - const saveSpy = jest.spyOn((component as any).actions, 'saveLicense'); - component.selectLicense({ id: 'lic-1', requiredFields: [] } as any); - expect((component.control() as FormGroup).get('id')?.value).toBe('lic-1'); - expect(saveSpy).toHaveBeenCalledWith('draft-1', 'lic-1'); + (store.dispatch as jest.Mock).mockClear(); + component.selectLicense(mockLicense); + expect(component.control().get('id')?.value).toBe('lic-1'); + expect(store.dispatch).toHaveBeenCalledWith(new SaveLicense('draft-1', 'lic-1')); }); it('should not save when license has required fields', () => { - const saveSpy = jest.spyOn((component as any).actions, 'saveLicense'); - component.selectLicense({ id: 'lic-2', requiredFields: ['year'] } as any); - expect(saveSpy).not.toHaveBeenCalled(); + (store.dispatch as jest.Mock).mockClear(); + component.selectLicense({ id: 'lic-2', name: 'CC-BY', requiredFields: ['year'], url: '', text: '' }); + expect(store.dispatch).not.toHaveBeenCalled(); }); - it('should create license with options', () => { - const saveSpy = jest.spyOn((component as any).actions, 'saveLicense'); - component.createLicense({ id: 'lic-3', licenseOptions: { year: '2024', copyrightHolders: 'Me' } as any }); - expect(saveSpy).toHaveBeenCalledWith('draft-1', 'lic-3', { year: '2024', copyrightHolders: 'Me' }); + it('should dispatch saveLicense with options on createLicense', () => { + (store.dispatch as jest.Mock).mockClear(); + component.createLicense({ id: 'lic-3', licenseOptions: { year: '2024', copyrightHolders: 'Me' } }); + expect(store.dispatch).toHaveBeenCalledWith( + new SaveLicense('draft-1', 'lic-3', { year: '2024', copyrightHolders: 'Me' }) + ); + }); + + it('should not apply default license when defaultLicenseId is not in the list', () => { + (store.dispatch as jest.Mock).mockClear(); + draftRegistrationSignal.set({ providerId: 'osf', defaultLicenseId: 'non-existent' }); + licensesSignal.set([mockLicense]); + fixture.detectChanges(); + expect(component.control().get('id')?.value).toBe(''); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(SaveLicense)); }); it('should mark control on focus out', () => { - const control = new FormGroup({ id: new FormControl('') }); - fixture.componentRef.setInput('control', control); - const spy = jest.spyOn(control, 'updateValueAndValidity'); component.onFocusOut(); - expect(control.touched).toBe(true); - expect(control.dirty).toBe(true); - expect(spy).toHaveBeenCalled(); + expect(component.control().touched).toBe(true); + expect(component.control().dirty).toBe(true); }); }); diff --git a/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.ts b/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.ts index a33da20e0..7225338ca 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-license/registries-license.component.ts @@ -5,113 +5,100 @@ import { TranslatePipe } from '@ngx-translate/core'; import { Card } from 'primeng/card'; import { Message } from 'primeng/message'; -import { ChangeDetectionStrategy, Component, effect, inject, input } from '@angular/core'; -import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; -import { ActivatedRoute } from '@angular/router'; +import { ChangeDetectionStrategy, Component, effect, inject, input, signal } from '@angular/core'; +import { FormGroup, ReactiveFormsModule } from '@angular/forms'; import { ENVIRONMENT } from '@core/provider/environment.provider'; import { FetchLicenses, RegistriesSelectors, SaveLicense } from '@osf/features/registries/store'; import { LicenseComponent } from '@osf/shared/components/license/license.component'; -import { InputLimits } from '@osf/shared/constants/input-limits.const'; import { INPUT_VALIDATION_MESSAGES } from '@osf/shared/constants/input-validation-messages.const'; import { LicenseModel, LicenseOptions } from '@shared/models/license/license.model'; @Component({ selector: 'osf-registries-license', - imports: [FormsModule, ReactiveFormsModule, LicenseComponent, Card, TranslatePipe, Message], + imports: [ReactiveFormsModule, LicenseComponent, Card, TranslatePipe, Message], templateUrl: './registries-license.component.html', styleUrl: './registries-license.component.scss', changeDetection: ChangeDetectionStrategy.OnPush, }) export class RegistriesLicenseComponent { control = input.required(); + draftId = input.required(); - private readonly route = inject(ActivatedRoute); private readonly environment = inject(ENVIRONMENT); - private readonly draftId = this.route.snapshot.params['id']; actions = createDispatchMap({ fetchLicenses: FetchLicenses, saveLicense: SaveLicense }); - licenses = select(RegistriesSelectors.getLicenses); - inputLimits = InputLimits; + licenses = select(RegistriesSelectors.getLicenses); selectedLicense = select(RegistriesSelectors.getSelectedLicense); draftRegistration = select(RegistriesSelectors.getDraftRegistration); - currentYear = new Date(); - readonly INPUT_VALIDATION_MESSAGES = INPUT_VALIDATION_MESSAGES; - private isLoaded = false; + private readonly licensesLoaded = signal(false); constructor() { effect(() => { - if (this.draftRegistration() && !this.isLoaded) { + if (this.draftRegistration() && !this.licensesLoaded()) { this.actions.fetchLicenses(this.draftRegistration()?.providerId ?? this.environment.defaultProvider); - this.isLoaded = true; + this.licensesLoaded.set(true); } }); effect(() => { - const selectedLicense = this.selectedLicense(); - if (!selectedLicense) { - return; - } - - this.control().patchValue({ - id: selectedLicense.id, - }); - }); - - effect(() => { + const control = this.control(); const licenses = this.licenses(); const selectedLicense = this.selectedLicense(); const defaultLicenseId = this.draftRegistration()?.defaultLicenseId; - if (!licenses.length) { + if (selectedLicense && licenses.some((l) => l.id === selectedLicense.id)) { + control.patchValue({ id: selectedLicense.id }); return; } - if ( - defaultLicenseId && - (!selectedLicense?.id || !licenses.find((license) => license.id === selectedLicense?.id)) - ) { - const defaultLicense = licenses.find((license) => license.id === defaultLicenseId); - if (defaultLicense) { - this.control().patchValue({ - id: defaultLicense.id, - }); - this.control().markAsTouched(); - this.control().updateValueAndValidity(); - - if (!defaultLicense.requiredFields.length) { - this.actions.saveLicense(this.draftId, defaultLicense.id); - } - } - } + this.applyDefaultLicense(control, licenses, defaultLicenseId); }); } createLicense(licenseDetails: { id: string; licenseOptions: LicenseOptions }) { - this.actions.saveLicense(this.draftId, licenseDetails.id, licenseDetails.licenseOptions); + this.actions.saveLicense(this.draftId(), licenseDetails.id, licenseDetails.licenseOptions); } selectLicense(license: LicenseModel) { if (license.requiredFields.length) { return; } - this.control().patchValue({ - id: license.id, - }); - this.control().markAsTouched(); - this.control().updateValueAndValidity(); - this.actions.saveLicense(this.draftId, license.id); + + const control = this.control(); + control.patchValue({ id: license.id }); + control.markAsTouched(); + control.updateValueAndValidity(); + this.actions.saveLicense(this.draftId(), license.id); } onFocusOut() { - if (this.control()) { - this.control().markAsTouched(); - this.control().markAsDirty(); - this.control().updateValueAndValidity(); + const control = this.control(); + control.markAsTouched(); + control.markAsDirty(); + control.updateValueAndValidity(); + } + + private applyDefaultLicense(control: FormGroup, licenses: LicenseModel[], defaultLicenseId?: string) { + if (!licenses.length || !defaultLicenseId) { + return; + } + + const defaultLicense = licenses.find((license) => license.id === defaultLicenseId); + if (!defaultLicense) { + return; + } + + control.patchValue({ id: defaultLicense.id }); + control.markAsTouched(); + control.updateValueAndValidity(); + + if (!defaultLicense.requiredFields.length) { + this.actions.saveLicense(this.draftId(), defaultLicense.id); } } } diff --git a/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.html b/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.html index 98f184e8f..04af77dbc 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.html +++ b/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.html @@ -39,7 +39,6 @@

{{ 'common.labels.description' | translate }}

rows="5" cols="30" pTextarea - [ariaLabel]="'common.labels.description' | translate" > @if ( metadataForm.controls['description'].errors?.['required'] && @@ -54,11 +53,17 @@

{{ 'common.labels.description' | translate }}

- - - - - + + + + +
{ +describe('RegistriesMetadataStepComponent', () => { + ngMocks.faster(); + let component: RegistriesMetadataStepComponent; let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; - let mockRouter: ReturnType; + let store: Store; + let mockRouter: RouterMockType; + let stepsStateSignal: WritableSignal<{ invalid: boolean }[]>; - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build(); + const mockDraft = { ...MOCK_DRAFT_REGISTRATION, title: 'Test Title', description: 'Test Description' }; + + beforeEach(() => { + const mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build(); mockRouter = RouterMockBuilder.create().withUrl('/registries/osf/draft/draft-1/metadata').build(); + stepsStateSignal = signal<{ invalid: boolean }[]>([{ invalid: true }]); - await TestBed.configureTestingModule({ + TestBed.configureTestingModule({ imports: [ RegistriesMetadataStepComponent, - OSFTestingModule, + MockModule(TextareaModule), ...MockComponents( TextInputComponent, RegistriesContributorsComponent, @@ -47,20 +60,23 @@ describe.skip('RegistriesMetadataStepComponent', () => { ), ], providers: [ - MockProvider(ActivatedRoute, mockActivatedRoute), - MockProvider(Router, mockRouter), - MockProvider(CustomConfirmationService, { confirmDelete: jest.fn() }), + provideOSFCore(), + provideActivatedRouteMock(mockActivatedRoute), + provideRouterMock(mockRouter), + MockCustomConfirmationServiceProvider, provideMockStore({ signals: [ - { selector: RegistriesSelectors.getStepsState, value: { 0: { invalid: false } } }, + { selector: RegistriesSelectors.getDraftRegistration, value: mockDraft }, + { selector: RegistriesSelectors.getStepsState, value: stepsStateSignal }, + { selector: RegistriesSelectors.hasDraftAdminAccess, value: true }, { selector: ContributorsSelectors.getContributors, value: [] }, { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, - { selector: InstitutionsSelectors.getResourceInstitutions, value: [] }, ], }), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(RegistriesMetadataStepComponent); component = fixture.componentInstance; fixture.detectChanges(); @@ -70,66 +86,97 @@ describe.skip('RegistriesMetadataStepComponent', () => { expect(component).toBeTruthy(); }); - it('should initialize form with draft data', () => { - expect(component.metadataForm.value.title).toBe(' My Title '); - expect(component.metadataForm.value.description).toBe(' Description '); - expect(component.metadataForm.value.license).toEqual({ id: 'mit' }); + it('should initialize metadataForm with required controls', () => { + expect(component.metadataForm.get('title')).toBeTruthy(); + expect(component.metadataForm.get('description')).toBeTruthy(); + expect(component.metadataForm.get('contributors')).toBeTruthy(); + expect(component.metadataForm.get('subjects')).toBeTruthy(); + expect(component.metadataForm.get('tags')).toBeTruthy(); + expect(component.metadataForm.get('license.id')).toBeTruthy(); }); - it('should compute hasAdminAccess', () => { - expect(component.hasAdminAccess()).toBe(true); + it('should have form invalid when title is empty', () => { + component.metadataForm.patchValue({ title: '', description: 'Valid' }); + expect(component.metadataForm.get('title')?.valid).toBe(false); }); - it('should submit metadata, trim values and navigate to first step', () => { - const actionsMock = { - updateDraft: jest.fn().mockReturnValue({ pipe: () => ({ subscribe: jest.fn() }) }), - deleteDraft: jest.fn(), - clearState: jest.fn(), - updateStepState: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - const navSpy = jest.spyOn(TestBed.inject(Router), 'navigate'); + it('should submit metadata and navigate to step 1', () => { + component.metadataForm.patchValue({ title: 'New Title', description: 'New Desc' }); + (store.dispatch as jest.Mock).mockClear(); component.submitMetadata(); - expect(actionsMock.updateDraft).toHaveBeenCalledWith('draft-1', { - title: 'My Title', - description: 'Description', - }); - expect(navSpy).toHaveBeenCalledWith(['../1'], { - relativeTo: TestBed.inject(ActivatedRoute), - onSameUrlNavigation: 'reload', - }); + expect(store.dispatch).toHaveBeenCalledWith( + new UpdateDraft('draft-1', { title: 'New Title', description: 'New Desc' }) + ); + expect(mockRouter.navigate).toHaveBeenCalledWith( + ['../1'], + expect.objectContaining({ onSameUrlNavigation: 'reload' }) + ); }); - it('should delete draft on confirm and navigate to new registration', () => { - const confirmService = TestBed.inject(CustomConfirmationService) as jest.Mocked as any; - const actionsMock = { - deleteDraft: jest.fn().mockReturnValue({ subscribe: ({ next }: any) => next() }), - clearState: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - const navSpy = jest.spyOn(TestBed.inject(Router), 'navigateByUrl'); + it('should trim title and description on submit', () => { + component.metadataForm.patchValue({ title: ' Padded Title ', description: ' Padded Desc ' }); + (store.dispatch as jest.Mock).mockClear(); - (confirmService.confirmDelete as jest.Mock).mockImplementation(({ onConfirm }) => onConfirm()); + component.submitMetadata(); + expect(store.dispatch).toHaveBeenCalledWith( + new UpdateDraft('draft-1', { title: 'Padded Title', description: 'Padded Desc' }) + ); + }); + + it('should call confirmDelete when deleteDraft is called', () => { component.deleteDraft(); + expect(CustomConfirmationServiceMock.confirmDelete).toHaveBeenCalledWith( + expect.objectContaining({ + headerKey: 'registries.deleteDraft', + messageKey: 'registries.confirmDeleteDraft', + }) + ); + }); - expect(actionsMock.clearState).toHaveBeenCalled(); - expect(navSpy).toHaveBeenCalledWith('/registries/osf/new'); + it('should set isDraftDeleted and navigate on deleteDraft confirm', () => { + CustomConfirmationServiceMock.confirmDelete.mockImplementation(({ onConfirm }: any) => onConfirm()); + (store.dispatch as jest.Mock).mockClear(); + + component.deleteDraft(); + + expect(component.isDraftDeleted).toBe(true); + expect(store.dispatch).toHaveBeenCalledWith(new DeleteDraft('draft-1')); + expect(store.dispatch).toHaveBeenCalledWith(new ClearState()); + expect(mockRouter.navigateByUrl).toHaveBeenCalledWith('/registries/osf/new'); + }); + + it('should skip updates on destroy when isDraftDeleted is true', () => { + (store.dispatch as jest.Mock).mockClear(); + component.isDraftDeleted = true; + component.ngOnDestroy(); + + expect(store.dispatch).not.toHaveBeenCalled(); }); - it('should update step state and draft on destroy if changed', () => { - const actionsMock = { - updateStepState: jest.fn(), - updateDraft: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); + it('should update step state on destroy when fields are unchanged', () => { + component.metadataForm.patchValue({ title: 'Test Title', description: 'Test Description' }); + (store.dispatch as jest.Mock).mockClear(); + component.ngOnDestroy(); + + expect(store.dispatch).toHaveBeenCalledWith(new UpdateStepState('0', expect.any(Boolean), true)); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(UpdateDraft)); + }); - component.metadataForm.patchValue({ title: 'Changed', description: 'Changed desc' }); - fixture.destroy(); + it('should dispatch updateDraft on destroy when fields have changed', () => { + component.metadataForm.patchValue({ title: 'Changed Title', description: 'Test Description' }); + (store.dispatch as jest.Mock).mockClear(); + component.ngOnDestroy(); + + expect(store.dispatch).toHaveBeenCalledWith(new UpdateStepState('0', expect.any(Boolean), true)); + expect(store.dispatch).toHaveBeenCalledWith( + new UpdateDraft('draft-1', expect.objectContaining({ title: 'Changed Title' })) + ); + }); - expect(actionsMock.updateStepState).toHaveBeenCalledWith('0', true, true); - expect(actionsMock.updateDraft).toHaveBeenCalledWith('draft-1', { title: 'Changed', description: 'Changed desc' }); + it('should mark form as touched when step state is invalid on init', () => { + expect(component.metadataForm.touched).toBe(true); }); }); diff --git a/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.ts b/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.ts index bfcc1e5f0..589ec9174 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.ts @@ -7,9 +7,10 @@ import { Card } from 'primeng/card'; import { Message } from 'primeng/message'; import { TextareaModule } from 'primeng/textarea'; -import { tap } from 'rxjs'; +import { filter, take, tap } from 'rxjs'; -import { ChangeDetectionStrategy, Component, computed, effect, inject, OnDestroy } from '@angular/core'; +import { ChangeDetectionStrategy, Component, DestroyRef, inject, OnDestroy } from '@angular/core'; +import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; @@ -21,7 +22,6 @@ import { findChangedFields } from '@osf/shared/helpers/find-changed-fields'; import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { ContributorsSelectors } from '@osf/shared/stores/contributors'; import { SubjectsSelectors } from '@osf/shared/stores/subjects'; -import { UserPermissions } from '@shared/enums/user-permissions.enum'; import { ContributorModel } from '@shared/models/contributors/contributor.model'; import { DraftRegistrationModel } from '@shared/models/registration/draft-registration.model'; import { SubjectModel } from '@shared/models/subject/subject.model'; @@ -58,21 +58,18 @@ export class RegistriesMetadataStepComponent implements OnDestroy { private readonly fb = inject(FormBuilder); private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); + private readonly destroyRef = inject(DestroyRef); private readonly customConfirmationService = inject(CustomConfirmationService); readonly titleLimit = InputLimits.title.maxLength; - private readonly draftId = this.route.snapshot.params['id']; - readonly draftRegistration = select(RegistriesSelectors.getDraftRegistration); + readonly draftId = this.route.snapshot.params['id']; + + draftRegistration = select(RegistriesSelectors.getDraftRegistration); selectedSubjects = select(SubjectsSelectors.getSelectedSubjects); initialContributors = select(ContributorsSelectors.getContributors); stepsState = select(RegistriesSelectors.getStepsState); - - hasAdminAccess = computed(() => { - const registry = this.draftRegistration(); - if (!registry) return false; - return registry.currentUserPermissions.includes(UserPermissions.Admin); - }); + hasAdminAccess = select(RegistriesSelectors.hasDraftAdminAccess); actions = createDispatchMap({ deleteDraft: DeleteDraft, @@ -89,35 +86,29 @@ export class RegistriesMetadataStepComponent implements OnDestroy { contributors: [[] as ContributorModel[], Validators.required], subjects: [[] as SubjectModel[], Validators.required], tags: [[]], - license: this.fb.group({ - id: ['', Validators.required], - }), + license: this.fb.group({ id: ['', Validators.required] }), }); isDraftDeleted = false; - isFormUpdated = false; constructor() { - effect(() => { - const draft = this.draftRegistration(); - // TODO: This shouldn't be an effect() - if (draft && !this.isFormUpdated) { - this.updateFormValue(draft); - this.isFormUpdated = true; - } - }); + toObservable(this.draftRegistration) + .pipe(filter(Boolean), take(1), takeUntilDestroyed(this.destroyRef)) + .subscribe((draft) => this.updateFormValue(draft)); } - private updateFormValue(data: DraftRegistrationModel): void { - this.metadataForm.patchValue({ - title: data.title, - description: data.description, - license: data.license, - contributors: this.initialContributors(), - subjects: this.selectedSubjects(), - }); - if (this.stepsState()?.[0]?.invalid) { - this.metadataForm.markAllAsTouched(); + ngOnDestroy(): void { + if (!this.isDraftDeleted) { + this.actions.updateStepState('0', this.metadataForm.invalid, true); + const changedFields = findChangedFields( + { title: this.metadataForm.value.title!, description: this.metadataForm.value.description! }, + { title: this.draftRegistration()?.title, description: this.draftRegistration()?.description } + ); + + if (Object.keys(changedFields).length > 0) { + this.actions.updateDraft(this.draftId, changedFields); + this.metadataForm.markAllAsTouched(); + } } } @@ -156,17 +147,17 @@ export class RegistriesMetadataStepComponent implements OnDestroy { }); } - ngOnDestroy(): void { - if (!this.isDraftDeleted) { - this.actions.updateStepState('0', this.metadataForm.invalid, true); - const changedFields = findChangedFields( - { title: this.metadataForm.value.title!, description: this.metadataForm.value.description! }, - { title: this.draftRegistration()?.title, description: this.draftRegistration()?.description } - ); - if (Object.keys(changedFields).length > 0) { - this.actions.updateDraft(this.draftId, changedFields); - this.metadataForm.markAllAsTouched(); - } + private updateFormValue(data: DraftRegistrationModel): void { + this.metadataForm.patchValue({ + title: data.title, + description: data.description, + license: data.license, + contributors: this.initialContributors(), + subjects: this.selectedSubjects(), + }); + + if (this.stepsState()?.[0]?.invalid) { + this.metadataForm.markAllAsTouched(); } } } diff --git a/src/app/features/registries/components/registries-metadata-step/registries-subjects/registries-subjects.component.spec.ts b/src/app/features/registries/components/registries-metadata-step/registries-subjects/registries-subjects.component.spec.ts index 9c8ecbff4..f86e440b3 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-subjects/registries-subjects.component.spec.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-subjects/registries-subjects.component.spec.ts @@ -1,57 +1,58 @@ -import { MockComponent, MockProvider } from 'ng-mocks'; +import { Store } from '@ngxs/store'; -import { of } from 'rxjs'; +import { MockComponent } from 'ng-mocks'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { FormControl } from '@angular/forms'; -import { ActivatedRoute } from '@angular/router'; +import { FormControl, Validators } from '@angular/forms'; import { RegistriesSelectors } from '@osf/features/registries/store'; import { SubjectsComponent } from '@osf/shared/components/subjects/subjects.component'; import { ResourceType } from '@osf/shared/enums/resource-type.enum'; -import { SubjectsSelectors } from '@osf/shared/stores/subjects'; +import { + FetchChildrenSubjects, + FetchSelectedSubjects, + FetchSubjects, + SubjectsSelectors, + UpdateResourceSubjects, +} from '@osf/shared/stores/subjects'; +import { SubjectModel } from '@shared/models/subject/subject.model'; import { RegistriesSubjectsComponent } from './registries-subjects.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { MOCK_DRAFT_REGISTRATION } from '@testing/mocks/draft-registration.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('RegistriesSubjectsComponent', () => { let component: RegistriesSubjectsComponent; let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; + let store: Store; - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build(); - await TestBed.configureTestingModule({ - imports: [RegistriesSubjectsComponent, OSFTestingModule, MockComponent(SubjectsComponent)], + const mockSubjects: SubjectModel[] = [ + { id: 'sub-1', name: 'Subject 1' }, + { id: 'sub-2', name: 'Subject 2' }, + ]; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [RegistriesSubjectsComponent, MockComponent(SubjectsComponent)], providers: [ - MockProvider(ActivatedRoute, mockActivatedRoute), + provideOSFCore(), provideMockStore({ signals: [ - { selector: RegistriesSelectors.getDraftRegistration, value: { providerId: 'prov-1' } }, { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, - { selector: SubjectsSelectors.getSubjects, value: [] }, - { selector: SubjectsSelectors.getSearchedSubjects, value: [] }, - { selector: SubjectsSelectors.getSubjectsLoading, value: false }, - { selector: SubjectsSelectors.getSearchedSubjectsLoading, value: false }, { selector: SubjectsSelectors.areSelectedSubjectsLoading, value: false }, + { selector: RegistriesSelectors.getDraftRegistration, value: MOCK_DRAFT_REGISTRATION }, ], }), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(RegistriesSubjectsComponent); component = fixture.componentInstance; - fixture.componentRef.setInput('control', new FormControl([])); - const mockActions = { - fetchSubjects: jest.fn().mockReturnValue(of({})), - fetchSelectedSubjects: jest.fn().mockReturnValue(of({})), - fetchChildrenSubjects: jest.fn().mockReturnValue(of({})), - updateResourceSubjects: jest.fn().mockReturnValue(of({})), - } as any; - Object.defineProperty(component, 'actions', { value: mockActions }); + fixture.componentRef.setInput('control', new FormControl(null, Validators.required)); + fixture.componentRef.setInput('draftId', 'draft-1'); fixture.detectChanges(); }); @@ -59,33 +60,54 @@ describe('RegistriesSubjectsComponent', () => { expect(component).toBeTruthy(); }); - it('should fetch subjects and selected subjects on init', () => { - const actions = (component as any).actions; - expect(actions.fetchSubjects).toHaveBeenCalledWith(ResourceType.Registration, 'prov-1'); - expect(actions.fetchSelectedSubjects).toHaveBeenCalledWith('draft-1', ResourceType.DraftRegistration); + it('should dispatch fetchSubjects and fetchSelectedSubjects on init', () => { + expect(store.dispatch).toHaveBeenCalledWith( + new FetchSubjects(ResourceType.Registration, MOCK_DRAFT_REGISTRATION.providerId) + ); + expect(store.dispatch).toHaveBeenCalledWith(new FetchSelectedSubjects('draft-1', ResourceType.DraftRegistration)); }); - it('should fetch children on demand', () => { - const actions = (component as any).actions; + it('should dispatch fetchChildrenSubjects on getSubjectChildren', () => { + (store.dispatch as jest.Mock).mockClear(); component.getSubjectChildren('parent-1'); - expect(actions.fetchChildrenSubjects).toHaveBeenCalledWith('parent-1'); + expect(store.dispatch).toHaveBeenCalledWith(new FetchChildrenSubjects('parent-1')); }); - it('should search subjects', () => { - const actions = (component as any).actions; - component.searchSubjects('term'); - expect(actions.fetchSubjects).toHaveBeenCalledWith(ResourceType.Registration, 'prov-1', 'term'); + it('should dispatch fetchSubjects with search term on searchSubjects', () => { + (store.dispatch as jest.Mock).mockClear(); + component.searchSubjects('biology'); + expect(store.dispatch).toHaveBeenCalledWith( + new FetchSubjects(ResourceType.Registration, MOCK_DRAFT_REGISTRATION.providerId, 'biology') + ); }); - it('should update selected subjects and control state', () => { - const actions = (component as any).actions; - const nextSubjects = [{ id: 's1' } as any]; - component.updateSelectedSubjects(nextSubjects); - expect(actions.updateResourceSubjects).toHaveBeenCalledWith( - 'draft-1', - ResourceType.DraftRegistration, - nextSubjects + it('should dispatch updateResourceSubjects and update control on updateSelectedSubjects', () => { + (store.dispatch as jest.Mock).mockClear(); + component.updateSelectedSubjects(mockSubjects); + expect(store.dispatch).toHaveBeenCalledWith( + new UpdateResourceSubjects('draft-1', ResourceType.DraftRegistration, mockSubjects) ); - expect(component.control().value).toEqual(nextSubjects); + expect(component.control().value).toEqual(mockSubjects); + expect(component.control().touched).toBe(true); + expect(component.control().dirty).toBe(true); + }); + + it('should mark control as touched and dirty on focusout', () => { + component.onFocusOut(); + expect(component.control().touched).toBe(true); + expect(component.control().dirty).toBe(true); + }); + + it('should have invalid control when value is null', () => { + component.control().markAsTouched(); + component.control().updateValueAndValidity(); + expect(component.control().valid).toBe(false); + expect(component.control().errors?.['required']).toBeTruthy(); + }); + + it('should have valid control when subjects are set', () => { + component.updateControlState(mockSubjects); + expect(component.control().valid).toBe(true); + expect(component.control().errors).toBeNull(); }); }); diff --git a/src/app/features/registries/components/registries-metadata-step/registries-subjects/registries-subjects.component.ts b/src/app/features/registries/components/registries-metadata-step/registries-subjects/registries-subjects.component.ts index 01915ab96..9e0f38db6 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-subjects/registries-subjects.component.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-subjects/registries-subjects.component.ts @@ -5,9 +5,8 @@ import { TranslatePipe } from '@ngx-translate/core'; import { Card } from 'primeng/card'; import { Message } from 'primeng/message'; -import { ChangeDetectionStrategy, Component, effect, inject, input } from '@angular/core'; +import { ChangeDetectionStrategy, Component, effect, input, signal } from '@angular/core'; import { FormControl } from '@angular/forms'; -import { ActivatedRoute } from '@angular/router'; import { RegistriesSelectors } from '@osf/features/registries/store'; import { SubjectsComponent } from '@osf/shared/components/subjects/subjects.component'; @@ -31,8 +30,7 @@ import { SubjectModel } from '@shared/models/subject/subject.model'; }) export class RegistriesSubjectsComponent { control = input.required(); - private readonly route = inject(ActivatedRoute); - private readonly draftId = this.route.snapshot.params['id']; + draftId = input.required(); selectedSubjects = select(SubjectsSelectors.getSelectedSubjects); isSubjectsUpdating = select(SubjectsSelectors.areSelectedSubjectsLoading); @@ -47,14 +45,14 @@ export class RegistriesSubjectsComponent { readonly INPUT_VALIDATION_MESSAGES = INPUT_VALIDATION_MESSAGES; - private isLoaded = false; + private readonly isLoaded = signal(false); constructor() { effect(() => { - if (this.draftRegistration() && !this.isLoaded) { + if (this.draftRegistration() && !this.isLoaded()) { this.actions.fetchSubjects(ResourceType.Registration, this.draftRegistration()?.providerId); - this.actions.fetchSelectedSubjects(this.draftId, ResourceType.DraftRegistration); - this.isLoaded = true; + this.actions.fetchSelectedSubjects(this.draftId(), ResourceType.DraftRegistration); + this.isLoaded.set(true); } }); } @@ -69,23 +67,21 @@ export class RegistriesSubjectsComponent { updateSelectedSubjects(subjects: SubjectModel[]) { this.updateControlState(subjects); - this.actions.updateResourceSubjects(this.draftId, ResourceType.DraftRegistration, subjects); + this.actions.updateResourceSubjects(this.draftId(), ResourceType.DraftRegistration, subjects); } onFocusOut() { - if (this.control()) { - this.control().markAsTouched(); - this.control().markAsDirty(); - this.control().updateValueAndValidity(); - } + const control = this.control(); + control.markAsTouched(); + control.markAsDirty(); + control.updateValueAndValidity(); } updateControlState(value: SubjectModel[]) { - if (this.control()) { - this.control().setValue(value); - this.control().markAsTouched(); - this.control().markAsDirty(); - this.control().updateValueAndValidity(); - } + const control = this.control(); + control.setValue(value); + control.markAsTouched(); + control.markAsDirty(); + control.updateValueAndValidity(); } } diff --git a/src/app/features/registries/components/registries-metadata-step/registries-tags/registries-tags.component.spec.ts b/src/app/features/registries/components/registries-metadata-step/registries-tags/registries-tags.component.spec.ts index 4072f1ed6..914396af1 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-tags/registries-tags.component.spec.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-tags/registries-tags.component.spec.ts @@ -1,36 +1,34 @@ -import { of } from 'rxjs'; +import { Store } from '@ngxs/store'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { RegistriesSelectors } from '@osf/features/registries/store'; +import { RegistriesSelectors, UpdateDraft } from '@osf/features/registries/store'; import { RegistriesTagsComponent } from './registries-tags.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('RegistriesTagsComponent', () => { let component: RegistriesTagsComponent; let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; + let store: Store; - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'someId' }).build(); - - await TestBed.configureTestingModule({ - imports: [RegistriesTagsComponent, OSFTestingModule], + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [RegistriesTagsComponent], providers: [ - { provide: ActivatedRoute, useValue: mockActivatedRoute }, + provideOSFCore(), provideMockStore({ signals: [{ selector: RegistriesSelectors.getSelectedTags, value: [] }], }), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(RegistriesTagsComponent); component = fixture.componentInstance; + fixture.componentRef.setInput('draftId', 'someId'); fixture.detectChanges(); }); @@ -44,11 +42,7 @@ describe('RegistriesTagsComponent', () => { }); it('should update tags on change', () => { - const mockActions = { - updateDraft: jest.fn().mockReturnValue(of({})), - } as any; - Object.defineProperty(component, 'actions', { value: mockActions }); component.onTagsChanged(['a', 'b']); - expect(mockActions.updateDraft).toHaveBeenCalledWith('someId', { tags: ['a', 'b'] }); + expect(store.dispatch).toHaveBeenCalledWith(new UpdateDraft('someId', { tags: ['a', 'b'] })); }); }); diff --git a/src/app/features/registries/components/registries-metadata-step/registries-tags/registries-tags.component.ts b/src/app/features/registries/components/registries-metadata-step/registries-tags/registries-tags.component.ts index 5c8c32cd1..dcba22a36 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-tags/registries-tags.component.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-tags/registries-tags.component.ts @@ -4,8 +4,7 @@ import { TranslatePipe } from '@ngx-translate/core'; import { Card } from 'primeng/card'; -import { ChangeDetectionStrategy, Component, inject } from '@angular/core'; -import { ActivatedRoute } from '@angular/router'; +import { ChangeDetectionStrategy, Component, input } from '@angular/core'; import { RegistriesSelectors, UpdateDraft } from '@osf/features/registries/store'; import { TagsInputComponent } from '@osf/shared/components/tags-input/tags-input.component'; @@ -18,15 +17,13 @@ import { TagsInputComponent } from '@osf/shared/components/tags-input/tags-input changeDetection: ChangeDetectionStrategy.OnPush, }) export class RegistriesTagsComponent { - private readonly route = inject(ActivatedRoute); - private readonly draftId = this.route.snapshot.params['id']; - selectedTags = select(RegistriesSelectors.getSelectedTags); + draftId = input.required(); + + actions = createDispatchMap({ updateDraft: UpdateDraft }); - actions = createDispatchMap({ - updateDraft: UpdateDraft, - }); + selectedTags = select(RegistriesSelectors.getSelectedTags); onTagsChanged(tags: string[]): void { - this.actions.updateDraft(this.draftId, { tags }); + this.actions.updateDraft(this.draftId(), { tags }); } } diff --git a/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.ts b/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.ts index 25350b20b..5fc736156 100644 --- a/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.ts +++ b/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.ts @@ -7,7 +7,7 @@ import { Tree } from 'primeng/tree'; import { ChangeDetectionStrategy, Component, inject } from '@angular/core'; -import { ProjectShortInfoModel } from '../../models'; +import { ProjectShortInfoModel } from '../../models/project-short-info.model'; @Component({ selector: 'osf-select-components-dialog', @@ -19,6 +19,7 @@ import { ProjectShortInfoModel } from '../../models'; export class SelectComponentsDialogComponent { readonly dialogRef = inject(DynamicDialogRef); readonly config = inject(DynamicDialogConfig); + selectedComponents: TreeNode[] = []; parent: ProjectShortInfoModel = this.config.data.parent; components: TreeNode[] = []; @@ -37,10 +38,14 @@ export class SelectComponentsDialogComponent { this.selectedComponents.push({ key: this.parent.id }); } + continue() { + const selectedComponentsSet = new Set([...this.selectedComponents.map((c) => c.key!), this.parent.id]); + this.dialogRef.close([...selectedComponentsSet]); + } + private mapProjectToTreeNode = (project: ProjectShortInfoModel): TreeNode => { - this.selectedComponents.push({ - key: project.id, - }); + this.selectedComponents.push({ key: project.id }); + return { label: project.title, data: project.id, @@ -49,9 +54,4 @@ export class SelectComponentsDialogComponent { children: project.children?.map(this.mapProjectToTreeNode) ?? [], }; }; - - continue() { - const selectedComponentsSet = new Set([...this.selectedComponents.map((c) => c.key!), this.parent.id]); - this.dialogRef.close([...selectedComponentsSet]); - } } diff --git a/src/app/features/registries/constants/registrations-tabs.ts b/src/app/features/registries/constants/registrations-tabs.ts index accf00f00..067163eec 100644 --- a/src/app/features/registries/constants/registrations-tabs.ts +++ b/src/app/features/registries/constants/registrations-tabs.ts @@ -1,8 +1,8 @@ -import { TabOption } from '@osf/shared/models/tab-option.model'; +import { CustomOption } from '@osf/shared/models/select-option.model'; import { RegistrationTab } from '../enums'; -export const REGISTRATIONS_TABS: TabOption[] = [ +export const REGISTRATIONS_TABS: CustomOption[] = [ { label: 'common.labels.drafts', value: RegistrationTab.Drafts, diff --git a/src/app/features/registries/enums/registration-tab.enum.ts b/src/app/features/registries/enums/registration-tab.enum.ts index 67eeac498..c7270c341 100644 --- a/src/app/features/registries/enums/registration-tab.enum.ts +++ b/src/app/features/registries/enums/registration-tab.enum.ts @@ -1,4 +1,4 @@ export enum RegistrationTab { - Drafts, - Submitted, + Drafts = 'drafts', + Submitted = 'submitted', } diff --git a/src/app/features/registries/models/index.ts b/src/app/features/registries/models/index.ts deleted file mode 100644 index 101e1aeac..000000000 --- a/src/app/features/registries/models/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './project-short-info.model'; diff --git a/src/app/features/registries/pages/draft-registration-custom-step/draft-registration-custom-step.component.spec.ts b/src/app/features/registries/pages/draft-registration-custom-step/draft-registration-custom-step.component.spec.ts index 0534020da..c716f46fe 100644 --- a/src/app/features/registries/pages/draft-registration-custom-step/draft-registration-custom-step.component.spec.ts +++ b/src/app/features/registries/pages/draft-registration-custom-step/draft-registration-custom-step.component.spec.ts @@ -1,99 +1,94 @@ import { Store } from '@ngxs/store'; -import { MockComponent, MockProvider } from 'ng-mocks'; - -import { of } from 'rxjs'; +import { MockComponent } from 'ng-mocks'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute, Router } from '@angular/router'; -import { DraftRegistrationAttributesJsonApi } from '@osf/shared/models/registration/registration-json-api.model'; +import { RegistriesSelectors, UpdateDraft } from '@osf/features/registries/store'; +import { DraftRegistrationModel } from '@osf/shared/models/registration/draft-registration.model'; import { CustomStepComponent } from '../../components/custom-step/custom-step.component'; -import { RegistriesSelectors, UpdateDraft } from '../../store'; import { DraftRegistrationCustomStepComponent } from './draft-registration-custom-step.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; -import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; +import { MOCK_REGISTRIES_PAGE } from '@testing/mocks/registries.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; +import { ActivatedRouteMockBuilder, provideActivatedRouteMock } from '@testing/providers/route-provider.mock'; +import { provideRouterMock, RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; +const MOCK_DRAFT: Partial = { + id: 'draft-1', + providerId: 'prov-1', + branchedFrom: { id: 'node-1', filesLink: '/files' }, +}; +const MOCK_STEPS_DATA: Record = { 'question-1': 'answer-1' }; + describe('DraftRegistrationCustomStepComponent', () => { let component: DraftRegistrationCustomStepComponent; let fixture: ComponentFixture; let store: Store; - let mockRouter: ReturnType; - let mockActivatedRoute: ReturnType; - - const mockStepsData = { stepKey: { field: 'value' } }; - const mockDraftRegistration = { - id: 'draft-1', - providerId: 'prov-1', - branchedFrom: { id: 'proj-1', filesLink: '/project/proj-1/files/' }, - }; - - beforeEach(async () => { - mockRouter = RouterMockBuilder.create().build(); - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build(); - - await TestBed.configureTestingModule({ - imports: [DraftRegistrationCustomStepComponent, OSFTestingModule, MockComponent(CustomStepComponent)], + let mockRouter: RouterMockType; + + function setup( + draft: Partial | null = MOCK_DRAFT, + stepsData: Record = MOCK_STEPS_DATA + ) { + const mockRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1', step: '1' }).build(); + mockRouter = RouterMockBuilder.create().withUrl('/registries/prov-1/draft/draft-1/custom').build(); + + TestBed.configureTestingModule({ + imports: [DraftRegistrationCustomStepComponent, MockComponent(CustomStepComponent)], providers: [ - MockProvider(Router, mockRouter), - MockProvider(ActivatedRoute, mockActivatedRoute), + provideOSFCore(), + provideActivatedRouteMock(mockRoute), + provideRouterMock(mockRouter), provideMockStore({ signals: [ - { selector: RegistriesSelectors.getStepsData, value: mockStepsData }, - { selector: RegistriesSelectors.getDraftRegistration, value: mockDraftRegistration }, + { selector: RegistriesSelectors.getStepsData, value: stepsData }, + { selector: RegistriesSelectors.getDraftRegistration, value: draft }, + { selector: RegistriesSelectors.getPagesSchema, value: [MOCK_REGISTRIES_PAGE] }, + { selector: RegistriesSelectors.getStepsState, value: { 1: { invalid: false } } }, ], }), ], - }).compileComponents(); + }); fixture = TestBed.createComponent(DraftRegistrationCustomStepComponent); component = fixture.componentInstance; store = TestBed.inject(Store); - (store.dispatch as jest.Mock).mockReturnValue(of(void 0)); fixture.detectChanges(); - }); + } it('should create', () => { + setup(); expect(component).toBeTruthy(); }); - it('should return stepsData and draftRegistration from store', () => { - expect(component.stepsData()).toEqual(mockStepsData); - expect(component.draftRegistration()).toEqual(mockDraftRegistration); - }); - - it('should compute filesLink from draftRegistration branchedFrom', () => { - expect(component.filesLink()).toBe('/project/proj-1/files/'); - }); - - it('should compute provider from draftRegistration providerId', () => { + it('should compute inputs from draft registration', () => { + setup(); + expect(component.filesLink()).toBe('/files'); expect(component.provider()).toBe('prov-1'); + expect(component.projectId()).toBe('node-1'); }); - it('should compute projectId from draftRegistration branchedFrom id', () => { - expect(component.projectId()).toBe('proj-1'); + it('should return empty strings when draftRegistration is null', () => { + setup(null, {}); + expect(component.filesLink()).toBe(''); + expect(component.provider()).toBe(''); + expect(component.projectId()).toBe(''); }); - it('should dispatch UpdateDraft with id and registration_responses payload on onUpdateAction', () => { - const attributes: Partial = { - registration_responses: { field1: 'value1' }, - }; - (store.dispatch as jest.Mock).mockClear(); - - component.onUpdateAction(attributes); - - expect(store.dispatch).toHaveBeenCalledWith(expect.any(UpdateDraft)); - const call = (store.dispatch as jest.Mock).mock.calls.find((c) => c[0] instanceof UpdateDraft); - expect(call[0].draftId).toBe('draft-1'); - expect(call[0].attributes).toEqual({ registration_responses: { registration_responses: { field1: 'value1' } } }); + it('should dispatch updateDraft with wrapped registration_responses', () => { + setup(); + component.onUpdateAction({ field1: 'value1', field2: ['a', 'b'] } as any); + expect(store.dispatch).toHaveBeenCalledWith( + new UpdateDraft('draft-1', { registration_responses: { field1: 'value1', field2: ['a', 'b'] } }) + ); }); - it('should navigate to ../metadata on onBack', () => { + it('should navigate back to metadata on onBack', () => { + setup(); component.onBack(); expect(mockRouter.navigate).toHaveBeenCalledWith( ['../', 'metadata'], @@ -101,7 +96,8 @@ describe('DraftRegistrationCustomStepComponent', () => { ); }); - it('should navigate to ../review on onNext', () => { + it('should navigate to review on onNext', () => { + setup(); component.onNext(); expect(mockRouter.navigate).toHaveBeenCalledWith( ['../', 'review'], @@ -109,34 +105,3 @@ describe('DraftRegistrationCustomStepComponent', () => { ); }); }); - -describe('DraftRegistrationCustomStepComponent when no draft registration', () => { - let component: DraftRegistrationCustomStepComponent; - let fixture: ComponentFixture; - - beforeEach(async () => { - await TestBed.configureTestingModule({ - imports: [DraftRegistrationCustomStepComponent, OSFTestingModule, MockComponent(CustomStepComponent)], - providers: [ - MockProvider(Router, RouterMockBuilder.create().build()), - MockProvider(ActivatedRoute, ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build()), - provideMockStore({ - signals: [ - { selector: RegistriesSelectors.getStepsData, value: {} }, - { selector: RegistriesSelectors.getDraftRegistration, value: null }, - ], - }), - ], - }).compileComponents(); - - fixture = TestBed.createComponent(DraftRegistrationCustomStepComponent); - component = fixture.componentInstance; - fixture.detectChanges(); - }); - - it('should compute empty filesLink provider and projectId', () => { - expect(component.filesLink()).toBe(''); - expect(component.provider()).toBe(''); - expect(component.projectId()).toBe(''); - }); -}); diff --git a/src/app/features/registries/pages/justification/justification.component.spec.ts b/src/app/features/registries/pages/justification/justification.component.spec.ts index ddbee0e57..00b39b835 100644 --- a/src/app/features/registries/pages/justification/justification.component.spec.ts +++ b/src/app/features/registries/pages/justification/justification.component.spec.ts @@ -1,87 +1,240 @@ -import { MockComponents, MockProvider } from 'ng-mocks'; +import { Store } from '@ngxs/store'; + +import { MockComponents } from 'ng-mocks'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute, Router } from '@angular/router'; +import { NavigationEnd } from '@angular/router'; -import { RegistriesSelectors } from '@osf/features/registries/store'; import { StepperComponent } from '@osf/shared/components/stepper/stepper.component'; import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header.component'; -import { LoaderService } from '@osf/shared/services/loader.service'; +import { RevisionReviewStates } from '@osf/shared/enums/revision-review-states.enum'; +import { PageSchema } from '@osf/shared/models/registration/page-schema.model'; +import { SchemaResponse } from '@osf/shared/models/registration/schema-response.model'; + +import { ClearState, FetchSchemaBlocks, FetchSchemaResponse, RegistriesSelectors } from '../../store'; import { JustificationComponent } from './justification.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; +import { createMockSchemaResponse } from '@testing/mocks/schema-response.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; +import { LoaderServiceMock, provideLoaderServiceMock } from '@testing/providers/loader-service.mock'; +import { ActivatedRouteMockBuilder, provideActivatedRouteMock } from '@testing/providers/route-provider.mock'; +import { provideRouterMock, RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; +const MOCK_SCHEMA_RESPONSE = createMockSchemaResponse('resp-1', RevisionReviewStates.RevisionInProgress); + +const MOCK_PAGES: PageSchema[] = [ + { id: 'page-1', title: 'Page One', questions: [{ id: 'q1', displayText: 'Q1', required: true, responseKey: 'q1' }] }, + { id: 'page-2', title: 'Page Two', questions: [{ id: 'q2', displayText: 'Q2', required: false, responseKey: 'q2' }] }, +]; + +interface SetupOptions { + routeParams?: Record; + routerUrl?: string; + schemaResponse?: SchemaResponse | null; + pages?: PageSchema[]; + stepsState?: Record; + revisionData?: Record; +} + describe('JustificationComponent', () => { let component: JustificationComponent; let fixture: ComponentFixture; - let mockActivatedRoute: Partial; - let mockRouter: ReturnType; - - beforeEach(async () => { - mockActivatedRoute = { - snapshot: { - firstChild: { params: { id: 'rev-1', step: '0' } } as any, - } as any, - firstChild: { snapshot: { params: { id: 'rev-1', step: '0' } } } as any, - } as Partial; - mockRouter = RouterMockBuilder.create().withUrl('/registries/revisions/rev-1/justification').build(); - - await TestBed.configureTestingModule({ - imports: [JustificationComponent, OSFTestingModule, ...MockComponents(StepperComponent, SubHeaderComponent)], + let store: Store; + let mockRouter: RouterMockType; + let routerBuilder: RouterMockBuilder; + let loaderService: LoaderServiceMock; + + function setup(options: SetupOptions = {}) { + const { + routeParams = { id: 'rev-1' }, + routerUrl = '/registries/revisions/rev-1/justification', + schemaResponse = MOCK_SCHEMA_RESPONSE, + pages = MOCK_PAGES, + stepsState = {}, + revisionData = MOCK_SCHEMA_RESPONSE.revisionResponses, + } = options; + + routerBuilder = RouterMockBuilder.create().withUrl(routerUrl); + mockRouter = routerBuilder.build(); + loaderService = new LoaderServiceMock(); + + const mockRoute = ActivatedRouteMockBuilder.create() + .withFirstChild((child) => child.withParams(routeParams)) + .build(); + + TestBed.configureTestingModule({ + imports: [JustificationComponent, ...MockComponents(StepperComponent, SubHeaderComponent)], providers: [ - MockProvider(ActivatedRoute, mockActivatedRoute), - MockProvider(Router, mockRouter), - MockProvider(LoaderService, { show: jest.fn(), hide: jest.fn() }), + provideOSFCore(), + provideActivatedRouteMock(mockRoute), + provideRouterMock(mockRouter), + provideLoaderServiceMock(loaderService), provideMockStore({ signals: [ - { selector: RegistriesSelectors.getPagesSchema, value: [] }, - { selector: RegistriesSelectors.getStepsState, value: { 0: { invalid: false, touched: false } } }, - { - selector: RegistriesSelectors.getSchemaResponse, - value: { - registrationSchemaId: 'schema-1', - revisionJustification: 'Reason', - reviewsState: 'revision_in_progress', - }, - }, - { selector: RegistriesSelectors.getSchemaResponseRevisionData, value: {} }, + { selector: RegistriesSelectors.getSchemaResponse, value: schemaResponse }, + { selector: RegistriesSelectors.getPagesSchema, value: pages }, + { selector: RegistriesSelectors.getStepsState, value: stepsState }, + { selector: RegistriesSelectors.getSchemaResponseRevisionData, value: revisionData }, ], }), ], - }).compileComponents(); + }); fixture = TestBed.createComponent(JustificationComponent); component = fixture.componentInstance; + store = TestBed.inject(Store); fixture.detectChanges(); - }); + } it('should create', () => { + setup(); expect(component).toBeTruthy(); }); - it('should compute steps with justification and review', () => { + it('should extract revisionId from route params', () => { + setup({ routeParams: { id: 'rev-42' } }); + expect(component.revisionId).toBe('rev-42'); + }); + + it('should default revisionId to empty string when no id param', () => { + setup({ routeParams: {} }); + expect(component.revisionId).toBe(''); + }); + + it('should build justification as first and review as last step with custom steps in between', () => { + setup(); + const steps = component.steps(); + expect(steps.length).toBe(4); + expect(steps[0]).toEqual(expect.objectContaining({ index: 0, value: 'justification', routeLink: 'justification' })); + expect(steps[1]).toEqual(expect.objectContaining({ index: 1, label: 'Page One', value: 'page-1', routeLink: '1' })); + expect(steps[2]).toEqual(expect.objectContaining({ index: 2, label: 'Page Two', value: 'page-2', routeLink: '2' })); + expect(steps[3]).toEqual( + expect.objectContaining({ index: 3, value: 'review', routeLink: 'review', invalid: false }) + ); + }); + + it('should mark justification step as invalid when revisionJustification is empty', () => { + setup({ schemaResponse: { ...MOCK_SCHEMA_RESPONSE, revisionJustification: '' } }); + const step = component.steps()[0]; + expect(step.invalid).toBe(true); + expect(step.touched).toBe(false); + }); + + it('should disable steps when reviewsState is not RevisionInProgress', () => { + setup({ schemaResponse: createMockSchemaResponse('resp-1', RevisionReviewStates.Approved) }); + const steps = component.steps(); + expect(steps[0].disabled).toBe(true); + expect(steps[1].disabled).toBe(true); + }); + + it('should apply stepsState invalid/touched to custom steps', () => { + setup({ stepsState: { 1: { invalid: true, touched: true }, 2: { invalid: false, touched: false } } }); + const steps = component.steps(); + expect(steps[1]).toEqual(expect.objectContaining({ invalid: true, touched: true })); + expect(steps[2]).toEqual(expect.objectContaining({ invalid: false, touched: false })); + }); + + it('should handle null schemaResponse gracefully', () => { + setup({ schemaResponse: null }); + const step = component.steps()[0]; + expect(step.invalid).toBe(true); + expect(step.disabled).toBe(true); + }); + + it('should produce only justification and review when no pages', () => { + setup({ pages: [] }); const steps = component.steps(); expect(steps.length).toBe(2); expect(steps[0].value).toBe('justification'); - expect(steps[1].value).toBe('review'); + expect(steps[1]).toEqual(expect.objectContaining({ index: 1, value: 'review' })); + }); + + it('should initialize currentStepIndex from route step param', () => { + setup({ routeParams: { id: 'rev-1', step: '2' } }); + expect(component.currentStepIndex()).toBe(2); + }); + + it('should default currentStepIndex to 0 when no step param', () => { + setup(); + expect(component.currentStepIndex()).toBe(0); + }); + + it('should return the step at currentStepIndex', () => { + setup(); + component.currentStepIndex.set(0); + expect(component.currentStep().value).toBe('justification'); + }); + + it('should update currentStepIndex and navigate on stepChange', () => { + setup(); + component.stepChange({ index: 1, label: 'Page One', value: 'page-1' } as any); + expect(component.currentStepIndex()).toBe(1); + expect(mockRouter.navigate).toHaveBeenCalledWith(['/registries/revisions/rev-1/', '1']); + }); + + it('should navigate to review route for last step', () => { + setup(); + const reviewIndex = component.steps().length - 1; + component.stepChange({ index: reviewIndex, label: 'Review', value: 'review' } as any); + expect(mockRouter.navigate).toHaveBeenCalledWith(['/registries/revisions/rev-1/', 'review']); + }); + + it('should update currentStepIndex on NavigationEnd', () => { + setup({ routeParams: { id: 'rev-1', step: '2' }, routerUrl: '/registries/revisions/rev-1/2' }); + routerBuilder.emit(new NavigationEnd(1, '/test', '/test')); + expect(component.currentStepIndex()).toBe(2); + }); + + it('should show loader on init', () => { + setup(); + expect(loaderService.show).toHaveBeenCalled(); + }); + + it('should dispatch FetchSchemaResponse when not already loaded', () => { + setup({ schemaResponse: null }); + expect(store.dispatch).toHaveBeenCalledWith(new FetchSchemaResponse('rev-1')); + }); + + it('should not dispatch FetchSchemaResponse when already loaded', () => { + setup(); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(FetchSchemaResponse)); + }); + + it('should dispatch FetchSchemaBlocks when schemaResponse has registrationSchemaId', () => { + setup(); + expect(store.dispatch).toHaveBeenCalledWith(new FetchSchemaBlocks(MOCK_SCHEMA_RESPONSE.registrationSchemaId)); + }); + + it('should dispatch clearState on destroy', () => { + setup(); + (store.dispatch as jest.Mock).mockClear(); + component.ngOnDestroy(); + expect(store.dispatch).toHaveBeenCalledWith(new ClearState()); + }); + + it('should detect review page from URL', () => { + setup({ routerUrl: '/registries/revisions/rev-1/review' }); + expect(component['isReviewPage']).toBe(true); + }); + + it('should return false for isReviewPage when not on review', () => { + setup(); + expect(component['isReviewPage']).toBe(false); }); - it('should navigate on stepChange', () => { - const navSpy = jest.spyOn(TestBed.inject(Router), 'navigate'); - component.stepChange({ index: 1, routeLink: '1', value: 'p1', label: 'Page 1' } as any); - expect(navSpy).toHaveBeenCalledWith(['/registries/revisions/rev-1/', 'review']); + it('should set currentStepIndex to last step on NavigationEnd when on review page without step param', () => { + setup({ routeParams: { id: 'rev-1' }, routerUrl: '/registries/revisions/rev-1/review' }); + component.currentStepIndex.set(0); + routerBuilder.emit(new NavigationEnd(2, '/review', '/review')); + expect(component.currentStepIndex()).toBe(MOCK_PAGES.length + 1); }); - it('should clear state on destroy', () => { - const actionsMock = { - clearState: jest.fn(), - getSchemaBlocks: jest.fn().mockReturnValue({ pipe: () => ({ subscribe: () => {} }) }), - } as any; - Object.defineProperty(component as any, 'actions', { value: actionsMock }); - fixture.destroy(); - expect(actionsMock.clearState).toHaveBeenCalled(); + it('should reset currentStepIndex to 0 on NavigationEnd when not on review and no step param', () => { + setup({ routeParams: { id: 'rev-1' }, routerUrl: '/registries/revisions/rev-1/justification' }); + component.currentStepIndex.set(2); + routerBuilder.emit(new NavigationEnd(2, '/justification', '/justification')); + expect(component.currentStepIndex()).toBe(0); }); }); diff --git a/src/app/features/registries/pages/justification/justification.component.ts b/src/app/features/registries/pages/justification/justification.component.ts index e196e9038..610dfd668 100644 --- a/src/app/features/registries/pages/justification/justification.component.ts +++ b/src/app/features/registries/pages/justification/justification.component.ts @@ -2,7 +2,7 @@ import { createDispatchMap, select } from '@ngxs/store'; import { TranslatePipe, TranslateService } from '@ngx-translate/core'; -import { filter, tap } from 'rxjs'; +import { filter } from 'rxjs'; import { ChangeDetectionStrategy, @@ -12,7 +12,6 @@ import { effect, inject, OnDestroy, - Signal, signal, untracked, } from '@angular/core'; @@ -33,21 +32,14 @@ import { ClearState, FetchSchemaBlocks, FetchSchemaResponse, RegistriesSelectors templateUrl: './justification.component.html', styleUrl: './justification.component.scss', changeDetection: ChangeDetectionStrategy.OnPush, - providers: [TranslateService], }) export class JustificationComponent implements OnDestroy { private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); private readonly destroyRef = inject(DestroyRef); - private readonly loaderService = inject(LoaderService); private readonly translateService = inject(TranslateService); - readonly pages = select(RegistriesSelectors.getPagesSchema); - readonly stepsState = select(RegistriesSelectors.getStepsState); - readonly schemaResponse = select(RegistriesSelectors.getSchemaResponse); - readonly schemaResponseRevisionData = select(RegistriesSelectors.getSchemaResponseRevisionData); - private readonly actions = createDispatchMap({ getSchemaBlocks: FetchSchemaBlocks, clearState: ClearState, @@ -55,61 +47,79 @@ export class JustificationComponent implements OnDestroy { updateStepState: UpdateStepState, }); + readonly pages = select(RegistriesSelectors.getPagesSchema); + readonly stepsState = select(RegistriesSelectors.getStepsState); + readonly schemaResponse = select(RegistriesSelectors.getSchemaResponse); + readonly schemaResponseRevisionData = select(RegistriesSelectors.getSchemaResponseRevisionData); + + readonly revisionId = this.route.snapshot.firstChild?.params['id'] || ''; + get isReviewPage(): boolean { return this.router.url.includes('/review'); } - reviewStep!: StepOption; - justificationStep!: StepOption; - revisionId = this.route.snapshot.firstChild?.params['id'] || ''; + readonly steps = computed(() => { + const response = this.schemaResponse(); + const isJustificationValid = !!response?.revisionJustification; + const isDisabled = response?.reviewsState !== RevisionReviewStates.RevisionInProgress; + const stepState = this.stepsState(); + const pages = this.pages(); - steps: Signal = computed(() => { - const isJustificationValid = !!this.schemaResponse()?.revisionJustification; - this.justificationStep = { + const justificationStep: StepOption = { index: 0, value: 'justification', label: this.translateService.instant('registries.justification.step'), invalid: !isJustificationValid, touched: isJustificationValid, routeLink: 'justification', - disabled: this.schemaResponse()?.reviewsState !== RevisionReviewStates.RevisionInProgress, + disabled: isDisabled, }; - this.reviewStep = { - index: 1, + const customSteps: StepOption[] = pages.map((page, index) => ({ + index: index + 1, + label: page.title, + value: page.id, + routeLink: `${index + 1}`, + invalid: stepState?.[index + 1]?.invalid || false, + touched: stepState?.[index + 1]?.touched || false, + disabled: isDisabled, + })); + + const reviewStep: StepOption = { + index: customSteps.length + 1, value: 'review', label: this.translateService.instant('registries.review.step'), invalid: false, routeLink: 'review', }; - const stepState = this.stepsState(); - const customSteps = this.pages().map((page, index) => { - return { - index: index + 1, - label: page.title, - value: page.id, - routeLink: `${index + 1}`, - invalid: stepState?.[index + 1]?.invalid || false, - touched: stepState?.[index + 1]?.touched || false, - disabled: this.schemaResponse()?.reviewsState !== RevisionReviewStates.RevisionInProgress, - }; - }); - return [ - { ...this.justificationStep }, - ...customSteps, - { ...this.reviewStep, index: customSteps.length + 1, invalid: false }, - ]; + + return [justificationStep, ...customSteps, reviewStep]; }); currentStepIndex = signal( this.route.snapshot.firstChild?.params['step'] ? +this.route.snapshot.firstChild?.params['step'] : 0 ); - currentStep = computed(() => { - return this.steps()[this.currentStepIndex()]; - }); + currentStep = computed(() => this.steps()[this.currentStepIndex()]); constructor() { + this.initRouterListener(); + this.initDataFetching(); + this.initReviewPageSync(); + this.initStepValidation(); + } + + ngOnDestroy(): void { + this.actions.clearState(); + } + + stepChange(step: StepOption): void { + this.currentStepIndex.set(step.index); + const pageLink = this.steps()[step.index].routeLink; + this.router.navigate([`/registries/revisions/${this.revisionId}/`, pageLink]); + } + + private initRouterListener(): void { this.router.events .pipe( takeUntilDestroyed(this.destroyRef), @@ -120,47 +130,56 @@ export class JustificationComponent implements OnDestroy { if (step) { this.currentStepIndex.set(+step); } else if (this.isReviewPage) { - const reviewStepIndex = this.pages().length + 1; - this.currentStepIndex.set(reviewStepIndex); + this.currentStepIndex.set(this.pages().length + 1); } else { this.currentStepIndex.set(0); } }); + } + private initDataFetching(): void { this.loaderService.show(); + if (!this.schemaResponse()) { this.actions.getSchemaResponse(this.revisionId); } effect(() => { const registrationSchemaId = this.schemaResponse()?.registrationSchemaId; + if (registrationSchemaId) { - this.actions - .getSchemaBlocks(registrationSchemaId) - .pipe(tap(() => this.loaderService.hide())) - .subscribe(); + this.actions.getSchemaBlocks(registrationSchemaId).subscribe(() => this.loaderService.hide()); } }); + } + private initReviewPageSync(): void { effect(() => { const reviewStepIndex = this.pages().length + 1; + if (this.isReviewPage) { this.currentStepIndex.set(reviewStepIndex); } }); + } + private initStepValidation(): void { effect(() => { + const currentIndex = this.currentStepIndex(); + const pages = this.pages(); + const revisionData = this.schemaResponseRevisionData(); const stepState = untracked(() => this.stepsState()); - if (this.currentStepIndex() > 0) { + if (currentIndex > 0) { this.actions.updateStepState('0', true, stepState?.[0]?.touched || false); } - if (this.pages().length && this.currentStepIndex() > 0 && this.schemaResponseRevisionData()) { - for (let i = 1; i < this.currentStepIndex(); i++) { - const pageStep = this.pages()[i - 1]; + + if (pages.length && currentIndex > 0 && revisionData) { + for (let i = 1; i < currentIndex; i++) { + const pageStep = pages[i - 1]; const isStepInvalid = pageStep?.questions?.some((question) => { - const questionData = this.schemaResponseRevisionData()[question.responseKey!]; + const questionData = revisionData[question.responseKey!]; return question.required && (Array.isArray(questionData) ? !questionData.length : !questionData); }) || false; this.actions.updateStepState(i.toString(), isStepInvalid, stepState?.[i]?.touched || false); @@ -168,14 +187,4 @@ export class JustificationComponent implements OnDestroy { } }); } - - stepChange(step: StepOption): void { - this.currentStepIndex.set(step.index); - const pageLink = this.steps()[step.index].routeLink; - this.router.navigate([`/registries/revisions/${this.revisionId}/`, pageLink]); - } - - ngOnDestroy(): void { - this.actions.clearState(); - } } diff --git a/src/app/features/registries/pages/my-registrations-redirect/my-registrations-redirect.component.spec.ts b/src/app/features/registries/pages/my-registrations-redirect/my-registrations-redirect.component.spec.ts index d4f40e53f..b82eba951 100644 --- a/src/app/features/registries/pages/my-registrations-redirect/my-registrations-redirect.component.spec.ts +++ b/src/app/features/registries/pages/my-registrations-redirect/my-registrations-redirect.component.spec.ts @@ -28,24 +28,10 @@ describe('MyRegistrationsRedirectComponent', () => { expect(component).toBeTruthy(); }); - it('should be an instance of MyRegistrationsRedirectComponent', () => { - expect(component).toBeInstanceOf(MyRegistrationsRedirectComponent); - }); - it('should navigate to /my-registrations on component creation', () => { expect(router.navigate).toHaveBeenCalledWith(['/my-registrations'], { queryParamsHandling: 'preserve', replaceUrl: true, }); }); - - it('should preserve query parameters during navigation', () => { - const navigationOptions = router.navigate.mock.calls[0][1]; - expect(navigationOptions?.queryParamsHandling).toBe('preserve'); - }); - - it('should replace the current URL in browser history', () => { - const navigationOptions = router.navigate.mock.calls[0][1]; - expect(navigationOptions?.replaceUrl).toBe(true); - }); }); diff --git a/src/app/features/registries/pages/my-registrations/my-registrations.component.html b/src/app/features/registries/pages/my-registrations/my-registrations.component.html index d9197ccaa..45a6b4e5f 100644 --- a/src/app/features/registries/pages/my-registrations/my-registrations.component.html +++ b/src/app/features/registries/pages/my-registrations/my-registrations.component.html @@ -10,7 +10,7 @@
- + @if (!isMobile()) { @for (tab of tabOptions; track tab.value) { diff --git a/src/app/features/registries/pages/my-registrations/my-registrations.component.spec.ts b/src/app/features/registries/pages/my-registrations/my-registrations.component.spec.ts index 5f1c0f4e4..b5bf6b208 100644 --- a/src/app/features/registries/pages/my-registrations/my-registrations.component.spec.ts +++ b/src/app/features/registries/pages/my-registrations/my-registrations.component.spec.ts @@ -1,9 +1,9 @@ -import { MockComponents, MockProvider } from 'ng-mocks'; +import { Store } from '@ngxs/store'; -import { of } from 'rxjs'; +import { MockComponents } from 'ng-mocks'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute, Router } from '@angular/router'; +import { ActivatedRoute } from '@angular/router'; import { UserSelectors } from '@core/store/user'; import { RegistrationTab } from '@osf/features/registries/enums'; @@ -15,35 +15,40 @@ import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { ToastService } from '@osf/shared/services/toast.service'; +import { DeleteDraft, FetchDraftRegistrations, FetchSubmittedRegistrations } from '../../store'; + import { MyRegistrationsComponent } from './my-registrations.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; +import { MockCustomConfirmationServiceProvider } from '@testing/mocks/custom-confirmation.service.mock'; +import { provideOSFCore, provideOSFToast } from '@testing/osf.testing.provider'; +import { ActivatedRouteMockBuilder, provideActivatedRouteMock } from '@testing/providers/route-provider.mock'; +import { provideRouterMock, RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('MyRegistrationsComponent', () => { let component: MyRegistrationsComponent; let fixture: ComponentFixture; - let mockRouter: ReturnType; - let mockActivatedRoute: Partial; + let store: Store; + let mockRoute: ReturnType; + let mockRouter: RouterMockType; let customConfirmationService: jest.Mocked; let toastService: jest.Mocked; - beforeEach(async () => { + function setup(queryParams: Record = {}) { mockRouter = RouterMockBuilder.create().withUrl('/registries/me').build(); - mockActivatedRoute = { snapshot: { queryParams: {} } } as any; + mockRoute = ActivatedRouteMockBuilder.create().withQueryParams(queryParams).build(); - await TestBed.configureTestingModule({ + TestBed.configureTestingModule({ imports: [ MyRegistrationsComponent, - OSFTestingModule, ...MockComponents(SubHeaderComponent, SelectComponent, RegistrationCardComponent, CustomPaginatorComponent), ], providers: [ - { provide: Router, useValue: mockRouter }, - { provide: ActivatedRoute, useValue: mockActivatedRoute }, - MockProvider(CustomConfirmationService, { confirmDelete: jest.fn() }), - MockProvider(ToastService, { showSuccess: jest.fn(), showWarn: jest.fn(), showError: jest.fn() }), + provideOSFCore(), + provideRouterMock(mockRouter), + provideActivatedRouteMock(mockRoute), + MockCustomConfirmationServiceProvider, + provideOSFToast(), provideMockStore({ signals: [ { selector: RegistriesSelectors.getDraftRegistrations, value: [] }, @@ -56,130 +61,109 @@ describe('MyRegistrationsComponent', () => { ], }), ], - }).compileComponents(); + }); fixture = TestBed.createComponent(MyRegistrationsComponent); component = fixture.componentInstance; + store = TestBed.inject(Store); customConfirmationService = TestBed.inject(CustomConfirmationService) as jest.Mocked; toastService = TestBed.inject(ToastService) as jest.Mocked; fixture.detectChanges(); - }); + } it('should create', () => { + setup(); expect(component).toBeTruthy(); }); - it('should default to submitted tab when no query param', () => { + it('should default to submitted tab and fetch submitted registrations', () => { + setup(); expect(component.selectedTab()).toBe(RegistrationTab.Submitted); + expect(store.dispatch).toHaveBeenCalledWith(new FetchSubmittedRegistrations()); }); - it('should switch to drafts tab when query param is drafts', () => { - (mockActivatedRoute.snapshot as any).queryParams = { tab: 'drafts' }; - - fixture = TestBed.createComponent(MyRegistrationsComponent); - component = fixture.componentInstance; - fixture.detectChanges(); - + it('should switch to drafts tab from query param and fetch drafts', () => { + setup({ tab: 'drafts' }); expect(component.selectedTab()).toBe(RegistrationTab.Drafts); + expect(store.dispatch).toHaveBeenCalledWith(new FetchDraftRegistrations()); }); - it('should switch to submitted tab when query param is submitted', () => { - (mockActivatedRoute.snapshot as any).queryParams = { tab: 'submitted' }; - - fixture = TestBed.createComponent(MyRegistrationsComponent); - component = fixture.componentInstance; - fixture.detectChanges(); - - expect(component.selectedTab()).toBe(RegistrationTab.Submitted); - }); - - it('should handle tab change and update query params', () => { - const actionsMock = { - getDraftRegistrations: jest.fn(), - getSubmittedRegistrations: jest.fn(), - deleteDraft: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - const navigateSpy = jest.spyOn(mockRouter, 'navigate'); + it('should change tab to drafts, reset pagination, fetch data, and update query params', () => { + setup(); + (store.dispatch as jest.Mock).mockClear(); + (mockRouter.navigate as jest.Mock).mockClear(); component.onTabChange(RegistrationTab.Drafts); expect(component.selectedTab()).toBe(RegistrationTab.Drafts); expect(component.draftFirst).toBe(0); - expect(actionsMock.getDraftRegistrations).toHaveBeenCalledWith(); - expect(navigateSpy).toHaveBeenCalledWith([], { - relativeTo: mockActivatedRoute, + expect(store.dispatch).toHaveBeenCalledWith(new FetchDraftRegistrations()); + expect(mockRouter.navigate).toHaveBeenCalledWith([], { + relativeTo: TestBed.inject(ActivatedRoute), queryParams: { tab: 'drafts' }, queryParamsHandling: 'merge', }); }); - it('should handle tab change to submitted and update query params', () => { - const actionsMock = { - getDraftRegistrations: jest.fn(), - getSubmittedRegistrations: jest.fn(), - deleteDraft: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - const navigateSpy = jest.spyOn(mockRouter, 'navigate'); + it('should change tab to submitted, reset pagination, fetch data, and update query params', () => { + setup(); + component.onTabChange(RegistrationTab.Drafts); + (store.dispatch as jest.Mock).mockClear(); + (mockRouter.navigate as jest.Mock).mockClear(); component.onTabChange(RegistrationTab.Submitted); expect(component.selectedTab()).toBe(RegistrationTab.Submitted); expect(component.submittedFirst).toBe(0); - expect(actionsMock.getSubmittedRegistrations).toHaveBeenCalledWith(); - expect(navigateSpy).toHaveBeenCalledWith([], { - relativeTo: mockActivatedRoute, + expect(store.dispatch).toHaveBeenCalledWith(new FetchSubmittedRegistrations()); + expect(mockRouter.navigate).toHaveBeenCalledWith([], { + relativeTo: TestBed.inject(ActivatedRoute), queryParams: { tab: 'submitted' }, queryParamsHandling: 'merge', }); }); - it('should not process tab change if tab is not a number', () => { - const actionsMock = { - getDraftRegistrations: jest.fn(), - getSubmittedRegistrations: jest.fn(), - deleteDraft: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); + it('should ignore invalid tab values', () => { + setup(); + (store.dispatch as jest.Mock).mockClear(); const initialTab = component.selectedTab(); - component.onTabChange('invalid' as any); + component.onTabChange('invalid'); + component.onTabChange(0); expect(component.selectedTab()).toBe(initialTab); - expect(actionsMock.getDraftRegistrations).not.toHaveBeenCalled(); - expect(actionsMock.getSubmittedRegistrations).not.toHaveBeenCalled(); + expect(store.dispatch).not.toHaveBeenCalled(); }); it('should navigate to create registration page', () => { - const navSpy = jest.spyOn(mockRouter, 'navigate'); + setup(); component.goToCreateRegistration(); - expect(navSpy).toHaveBeenLastCalledWith(['/registries', 'osf', 'new']); + expect(mockRouter.navigate).toHaveBeenCalledWith(['/registries', 'osf', 'new']); }); it('should handle drafts pagination', () => { - const actionsMock = { getDraftRegistrations: jest.fn() } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - component.onDraftsPageChange({ page: 2, first: 20 } as any); - expect(actionsMock.getDraftRegistrations).toHaveBeenCalledWith(3); + setup(); + (store.dispatch as jest.Mock).mockClear(); + + component.onDraftsPageChange({ page: 2, first: 20 }); + + expect(store.dispatch).toHaveBeenCalledWith(new FetchDraftRegistrations(3)); expect(component.draftFirst).toBe(20); }); it('should handle submitted pagination', () => { - const actionsMock = { getSubmittedRegistrations: jest.fn() } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - component.onSubmittedPageChange({ page: 1, first: 10 } as any); - expect(actionsMock.getSubmittedRegistrations).toHaveBeenCalledWith(2); + setup(); + (store.dispatch as jest.Mock).mockClear(); + + component.onSubmittedPageChange({ page: 1, first: 10 }); + + expect(store.dispatch).toHaveBeenCalledWith(new FetchSubmittedRegistrations(2)); expect(component.submittedFirst).toBe(10); }); it('should delete draft after confirmation', () => { - const actionsMock = { - getDraftRegistrations: jest.fn(), - getSubmittedRegistrations: jest.fn(), - deleteDraft: jest.fn(() => of({})), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); + setup(); + (store.dispatch as jest.Mock).mockClear(); customConfirmationService.confirmDelete.mockImplementation(({ onConfirm }) => { onConfirm(); }); @@ -191,53 +175,21 @@ describe('MyRegistrationsComponent', () => { messageKey: 'registries.confirmDeleteDraft', onConfirm: expect.any(Function), }); - expect(actionsMock.deleteDraft).toHaveBeenCalledWith('draft-123'); - expect(actionsMock.getDraftRegistrations).toHaveBeenCalled(); + expect(store.dispatch).toHaveBeenCalledWith(new DeleteDraft('draft-123')); + expect(store.dispatch).toHaveBeenCalledWith(new FetchDraftRegistrations()); expect(toastService.showSuccess).toHaveBeenCalledWith('registries.successDeleteDraft'); }); it('should not delete draft if confirmation is cancelled', () => { - const actionsMock = { - getDraftRegistrations: jest.fn(), - getSubmittedRegistrations: jest.fn(), - deleteDraft: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); + setup(); + (store.dispatch as jest.Mock).mockClear(); + toastService.showSuccess.mockClear(); customConfirmationService.confirmDelete.mockImplementation(() => {}); component.onDeleteDraft('draft-123'); expect(customConfirmationService.confirmDelete).toHaveBeenCalled(); - expect(actionsMock.deleteDraft).not.toHaveBeenCalled(); - expect(actionsMock.getDraftRegistrations).not.toHaveBeenCalled(); + expect(store.dispatch).not.toHaveBeenCalled(); expect(toastService.showSuccess).not.toHaveBeenCalled(); }); - - it('should reset draftFirst when switching to drafts tab', () => { - component.draftFirst = 20; - const actionsMock = { - getDraftRegistrations: jest.fn(), - getSubmittedRegistrations: jest.fn(), - deleteDraft: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - - component.onTabChange(RegistrationTab.Drafts); - - expect(component.draftFirst).toBe(0); - }); - - it('should reset submittedFirst when switching to submitted tab', () => { - component.submittedFirst = 20; - const actionsMock = { - getDraftRegistrations: jest.fn(), - getSubmittedRegistrations: jest.fn(), - deleteDraft: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - - component.onTabChange(RegistrationTab.Submitted); - - expect(component.submittedFirst).toBe(0); - }); }); diff --git a/src/app/features/registries/pages/my-registrations/my-registrations.component.ts b/src/app/features/registries/pages/my-registrations/my-registrations.component.ts index 106db16e9..95179b7b7 100644 --- a/src/app/features/registries/pages/my-registrations/my-registrations.component.ts +++ b/src/app/features/registries/pages/my-registrations/my-registrations.component.ts @@ -10,7 +10,6 @@ import { TabsModule } from 'primeng/tabs'; import { NgTemplateOutlet } from '@angular/common'; import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core'; import { toSignal } from '@angular/core/rxjs-interop'; -import { FormsModule } from '@angular/forms'; import { ActivatedRoute, Router, RouterLink } from '@angular/router'; import { ENVIRONMENT } from '@core/provider/environment.provider'; @@ -30,17 +29,16 @@ import { DeleteDraft, FetchDraftRegistrations, FetchSubmittedRegistrations, Regi @Component({ selector: 'osf-my-registrations', imports: [ - SubHeaderComponent, - TranslatePipe, - TabsModule, - FormsModule, - SelectComponent, - RegistrationCardComponent, - CustomPaginatorComponent, - Skeleton, Button, + Skeleton, + TabsModule, RouterLink, NgTemplateOutlet, + CustomPaginatorComponent, + RegistrationCardComponent, + SelectComponent, + SubHeaderComponent, + TranslatePipe, ], templateUrl: './my-registrations.component.html', styleUrl: './my-registrations.component.scss', @@ -82,26 +80,28 @@ export class MyRegistrationsComponent { constructor() { const initialTab = this.route.snapshot.queryParams['tab']; - const selectedTab = initialTab == 'drafts' ? RegistrationTab.Drafts : RegistrationTab.Submitted; + const selectedTab = initialTab === RegistrationTab.Drafts ? RegistrationTab.Drafts : RegistrationTab.Submitted; this.onTabChange(selectedTab); } onTabChange(tab: Primitive): void { - if (typeof tab !== 'number') { + if (typeof tab !== 'string' || !Object.values(RegistrationTab).includes(tab as RegistrationTab)) { return; } - this.selectedTab.set(tab); - this.loadTabData(tab); + const validTab = tab as RegistrationTab; + + this.selectedTab.set(validTab); + this.loadTabData(validTab); this.router.navigate([], { relativeTo: this.route, - queryParams: { tab: tab === RegistrationTab.Drafts ? 'drafts' : 'submitted' }, + queryParams: { tab }, queryParamsHandling: 'merge', }); } - private loadTabData(tab: number): void { + private loadTabData(tab: RegistrationTab): void { if (tab === RegistrationTab.Drafts) { this.draftFirst = 0; this.actions.getDraftRegistrations(); diff --git a/src/app/features/registries/pages/registries-landing/registries-landing.component.spec.ts b/src/app/features/registries/pages/registries-landing/registries-landing.component.spec.ts index cf4780553..7520a2198 100644 --- a/src/app/features/registries/pages/registries-landing/registries-landing.component.spec.ts +++ b/src/app/features/registries/pages/registries-landing/registries-landing.component.spec.ts @@ -1,36 +1,39 @@ +import { Store } from '@ngxs/store'; + import { MockComponents } from 'ng-mocks'; +import { PLATFORM_ID } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { Router } from '@angular/router'; import { ScheduledBannerComponent } from '@core/components/osf-banners/scheduled-banner/scheduled-banner.component'; +import { ClearCurrentProvider } from '@core/store/provider'; import { LoadingSpinnerComponent } from '@osf/shared/components/loading-spinner/loading-spinner.component'; import { ResourceCardComponent } from '@osf/shared/components/resource-card/resource-card.component'; import { SearchInputComponent } from '@osf/shared/components/search-input/search-input.component'; import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header.component'; -import { RegistrationProviderSelectors } from '@osf/shared/stores/registration-provider'; +import { ClearRegistryProvider, GetRegistryProvider } from '@osf/shared/stores/registration-provider'; import { RegistryServicesComponent } from '../../components/registry-services/registry-services.component'; -import { RegistriesSelectors } from '../../store'; +import { GetRegistries, RegistriesSelectors } from '../../store'; import { RegistriesLandingComponent } from './registries-landing.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; +import { provideRouterMock, RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('RegistriesLandingComponent', () => { let component: RegistriesLandingComponent; let fixture: ComponentFixture; - let mockRouter: ReturnType; + let store: Store; + let mockRouter: RouterMockType; - beforeEach(async () => { + beforeEach(() => { mockRouter = RouterMockBuilder.create().withUrl('/registries').build(); - await TestBed.configureTestingModule({ + TestBed.configureTestingModule({ imports: [ RegistriesLandingComponent, - OSFTestingModule, ...MockComponents( SearchInputComponent, RegistryServicesComponent, @@ -41,20 +44,21 @@ describe('RegistriesLandingComponent', () => { ), ], providers: [ - { provide: Router, useValue: mockRouter }, + provideOSFCore(), + provideRouterMock(mockRouter), + { provide: PLATFORM_ID, useValue: 'browser' }, provideMockStore({ signals: [ - { selector: RegistrationProviderSelectors.getBrandedProvider, value: null }, - { selector: RegistrationProviderSelectors.isBrandedProviderLoading, value: false }, { selector: RegistriesSelectors.getRegistries, value: [] }, { selector: RegistriesSelectors.isRegistriesLoading, value: false }, ], }), ], - }).compileComponents(); + }); fixture = TestBed.createComponent(RegistriesLandingComponent); component = fixture.componentInstance; + store = TestBed.inject(Store); fixture.detectChanges(); }); @@ -62,51 +66,31 @@ describe('RegistriesLandingComponent', () => { expect(component).toBeTruthy(); }); - it('should dispatch get registries and provider on init', () => { - const actionsMock = { - getRegistries: jest.fn(), - getProvider: jest.fn(), - clearCurrentProvider: jest.fn(), - clearRegistryProvider: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - - component.ngOnInit(); - - expect(actionsMock.getRegistries).toHaveBeenCalled(); - expect(actionsMock.getProvider).toHaveBeenCalledWith(component.defaultProvider); + it('should dispatch getRegistries and getProvider on init', () => { + expect(store.dispatch).toHaveBeenCalledWith(new GetRegistries()); + expect(store.dispatch).toHaveBeenCalledWith(new GetRegistryProvider(component.defaultProvider)); }); - it('should clear providers on destroy', () => { - const actionsMock = { - getRegistries: jest.fn(), - getProvider: jest.fn(), - clearCurrentProvider: jest.fn(), - clearRegistryProvider: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); - + it('should dispatch clear actions on destroy', () => { + (store.dispatch as jest.Mock).mockClear(); fixture.destroy(); - expect(actionsMock.clearCurrentProvider).toHaveBeenCalled(); - expect(actionsMock.clearRegistryProvider).toHaveBeenCalled(); + expect(store.dispatch).toHaveBeenCalledWith(new ClearCurrentProvider()); + expect(store.dispatch).toHaveBeenCalledWith(new ClearRegistryProvider()); }); it('should navigate to search with value', () => { - const navSpy = jest.spyOn(TestBed.inject(Router), 'navigate'); component.searchControl.setValue('abc'); component.redirectToSearchPageWithValue(); - expect(navSpy).toHaveBeenCalledWith(['/search'], { queryParams: { search: 'abc', tab: 3 } }); + expect(mockRouter.navigate).toHaveBeenCalledWith(['/search'], { queryParams: { search: 'abc', tab: 3 } }); }); it('should navigate to search registrations tab', () => { - const navSpy = jest.spyOn(TestBed.inject(Router), 'navigate'); component.redirectToSearchPageRegistrations(); - expect(navSpy).toHaveBeenCalledWith(['/search'], { queryParams: { tab: 3 } }); + expect(mockRouter.navigate).toHaveBeenCalledWith(['/search'], { queryParams: { tab: 3 } }); }); it('should navigate to create page', () => { - const navSpy = jest.spyOn(TestBed.inject(Router), 'navigate'); component.goToCreateRegistration(); - expect(navSpy).toHaveBeenCalledWith(['/registries/osf/new']); + expect(mockRouter.navigate).toHaveBeenCalledWith([`/registries/${component.defaultProvider}/new`]); }); }); diff --git a/src/app/features/registries/pages/registries-landing/registries-landing.component.ts b/src/app/features/registries/pages/registries-landing/registries-landing.component.ts index 1aa9c22c8..917caf2fc 100644 --- a/src/app/features/registries/pages/registries-landing/registries-landing.component.ts +++ b/src/app/features/registries/pages/registries-landing/registries-landing.component.ts @@ -18,11 +18,7 @@ import { SearchInputComponent } from '@osf/shared/components/search-input/search import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header.component'; import { ResourceType } from '@osf/shared/enums/resource-type.enum'; import { normalizeQuotes } from '@osf/shared/helpers/normalize-quotes'; -import { - ClearRegistryProvider, - GetRegistryProvider, - RegistrationProviderSelectors, -} from '@osf/shared/stores/registration-provider'; +import { ClearRegistryProvider, GetRegistryProvider } from '@osf/shared/stores/registration-provider'; import { RegistryServicesComponent } from '../../components/registry-services/registry-services.component'; import { GetRegistries, RegistriesSelectors } from '../../store'; @@ -44,10 +40,9 @@ import { GetRegistries, RegistriesSelectors } from '../../store'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class RegistriesLandingComponent implements OnInit, OnDestroy { - private router = inject(Router); + private readonly router = inject(Router); private readonly environment = inject(ENVIRONMENT); - private readonly platformId = inject(PLATFORM_ID); - private readonly isBrowser = isPlatformBrowser(this.platformId); + private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); private actions = createDispatchMap({ getRegistries: GetRegistries, @@ -56,8 +51,6 @@ export class RegistriesLandingComponent implements OnInit, OnDestroy { clearRegistryProvider: ClearRegistryProvider, }); - provider = select(RegistrationProviderSelectors.getBrandedProvider); - isProviderLoading = select(RegistrationProviderSelectors.isBrandedProviderLoading); registries = select(RegistriesSelectors.getRegistries); isRegistriesLoading = select(RegistriesSelectors.isRegistriesLoading); diff --git a/src/app/features/registries/pages/registries-provider-search/registries-provider-search.component.spec.ts b/src/app/features/registries/pages/registries-provider-search/registries-provider-search.component.spec.ts index 6498fed94..6f53ec22f 100644 --- a/src/app/features/registries/pages/registries-provider-search/registries-provider-search.component.spec.ts +++ b/src/app/features/registries/pages/registries-provider-search/registries-provider-search.component.spec.ts @@ -1,67 +1,115 @@ -import { MockComponents, MockProvider } from 'ng-mocks'; +import { Store } from '@ngxs/store'; +import { MockComponents } from 'ng-mocks'; + +import { PLATFORM_ID } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { RegistryProviderHeroComponent } from '@osf/features/registries/components/registry-provider-hero/registry-provider-hero.component'; +import { ClearCurrentProvider } from '@core/store/provider'; import { GlobalSearchComponent } from '@osf/shared/components/global-search/global-search.component'; -import { CustomDialogService } from '@osf/shared/services/custom-dialog.service'; -import { RegistrationProviderSelectors } from '@osf/shared/stores/registration-provider'; +import { ResourceType } from '@osf/shared/enums/resource-type.enum'; +import { RegistryProviderDetails } from '@osf/shared/models/provider/registry-provider.model'; +import { SetDefaultFilterValue, SetResourceType } from '@osf/shared/stores/global-search'; +import { + ClearRegistryProvider, + GetRegistryProvider, + RegistrationProviderSelectors, +} from '@osf/shared/stores/registration-provider'; + +import { RegistryProviderHeroComponent } from '../../components/registry-provider-hero/registry-provider-hero.component'; import { RegistriesProviderSearchComponent } from './registries-provider-search.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; +import { ActivatedRouteMockBuilder, provideActivatedRouteMock } from '@testing/providers/route-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; +const MOCK_PROVIDER: RegistryProviderDetails = { + id: 'provider-1', + name: 'Test Provider', + descriptionHtml: '', + permissions: [], + brand: null, + iri: 'http://iri.example.com', + reviewsWorkflow: 'pre-moderation', +}; + describe('RegistriesProviderSearchComponent', () => { let component: RegistriesProviderSearchComponent; let fixture: ComponentFixture; + let store: Store; - beforeEach(async () => { - const routeMock = ActivatedRouteMockBuilder.create().withParams({ name: 'osf' }).build(); + const PROVIDER_ID = 'provider-1'; - await TestBed.configureTestingModule({ + function setup(params: Record = { providerId: PROVIDER_ID }, platformId = 'browser') { + const mockRoute = ActivatedRouteMockBuilder.create().withParams(params).build(); + + TestBed.configureTestingModule({ imports: [ RegistriesProviderSearchComponent, - OSFTestingModule, - ...MockComponents(GlobalSearchComponent, RegistryProviderHeroComponent), + ...MockComponents(RegistryProviderHeroComponent, GlobalSearchComponent), ], providers: [ - { provide: ActivatedRoute, useValue: routeMock }, - MockProvider(CustomDialogService, { open: jest.fn() }), + provideOSFCore(), + provideActivatedRouteMock(mockRoute), + { provide: PLATFORM_ID, useValue: platformId }, provideMockStore({ signals: [ - { selector: RegistrationProviderSelectors.getBrandedProvider, value: { iri: 'http://iri/provider' } }, + { selector: RegistrationProviderSelectors.getBrandedProvider, value: MOCK_PROVIDER }, { selector: RegistrationProviderSelectors.isBrandedProviderLoading, value: false }, ], }), ], - }).compileComponents(); + }); fixture = TestBed.createComponent(RegistriesProviderSearchComponent); component = fixture.componentInstance; - }); + store = TestBed.inject(Store); + fixture.detectChanges(); + } it('should create', () => { - fixture.detectChanges(); + setup(); expect(component).toBeTruthy(); }); - it('should clear providers on destroy', () => { - fixture.detectChanges(); + it('should fetch provider and initialize search filters on init', () => { + setup(); + expect(store.dispatch).toHaveBeenCalledWith(new GetRegistryProvider(PROVIDER_ID)); + expect(store.dispatch).toHaveBeenCalledWith(new SetDefaultFilterValue('publisher', MOCK_PROVIDER.iri)); + expect(store.dispatch).toHaveBeenCalledWith(new SetResourceType(ResourceType.Registration)); + expect(component.defaultSearchFiltersInitialized()).toBe(true); + }); + + it('should initialize searchControl with empty string', () => { + setup(); + expect(component.searchControl.value).toBe(''); + }); + + it('should expose provider and isProviderLoading from store', () => { + setup(); + expect(component.provider()).toEqual(MOCK_PROVIDER); + expect(component.isProviderLoading()).toBe(false); + }); + + it('should dispatch clear actions on destroy in browser', () => { + setup(); + (store.dispatch as jest.Mock).mockClear(); + component.ngOnDestroy(); + expect(store.dispatch).toHaveBeenCalledWith(new ClearCurrentProvider()); + expect(store.dispatch).toHaveBeenCalledWith(new ClearRegistryProvider()); + }); + + it('should not fetch provider or initialize filters when providerId is missing', () => { + setup({}); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(GetRegistryProvider)); + expect(component.defaultSearchFiltersInitialized()).toBe(false); + }); - const actionsMock = { - getProvider: jest.fn(), - setDefaultFilterValue: jest.fn(), - setResourceType: jest.fn(), - clearCurrentProvider: jest.fn(), - clearRegistryProvider: jest.fn(), - } as any; - Object.defineProperty(component as any, 'actions', { value: actionsMock }); - - fixture.destroy(); - expect(actionsMock.clearCurrentProvider).toHaveBeenCalled(); - expect(actionsMock.clearRegistryProvider).toHaveBeenCalled(); + it('should not dispatch clear actions on destroy on server', () => { + setup({}, 'server'); + (store.dispatch as jest.Mock).mockClear(); + component.ngOnDestroy(); + expect(store.dispatch).not.toHaveBeenCalled(); }); }); diff --git a/src/app/features/registries/pages/revisions-custom-step/revisions-custom-step.component.spec.ts b/src/app/features/registries/pages/revisions-custom-step/revisions-custom-step.component.spec.ts index 6411524f3..86b056485 100644 --- a/src/app/features/registries/pages/revisions-custom-step/revisions-custom-step.component.spec.ts +++ b/src/app/features/registries/pages/revisions-custom-step/revisions-custom-step.component.spec.ts @@ -1,33 +1,35 @@ -import { MockComponents, MockProvider } from 'ng-mocks'; +import { Store } from '@ngxs/store'; + +import { MockComponents } from 'ng-mocks'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute, Router } from '@angular/router'; import { CustomStepComponent } from '../../components/custom-step/custom-step.component'; -import { RegistriesSelectors } from '../../store'; +import { RegistriesSelectors, UpdateSchemaResponse } from '../../store'; import { RevisionsCustomStepComponent } from './revisions-custom-step.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; -import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; +import { ActivatedRouteMockBuilder, provideActivatedRouteMock } from '@testing/providers/route-provider.mock'; +import { provideRouterMock, RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('RevisionsCustomStepComponent', () => { let component: RevisionsCustomStepComponent; let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; - let mockRouter: ReturnType; + let store: Store; + let mockRouter: RouterMockType; - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'rev-1', step: '1' }).build(); + beforeEach(() => { + const mockRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'rev-1', step: '1' }).build(); mockRouter = RouterMockBuilder.create().withUrl('/registries/revisions/rev-1/1').build(); - await TestBed.configureTestingModule({ - imports: [RevisionsCustomStepComponent, OSFTestingModule, MockComponents(CustomStepComponent)], + TestBed.configureTestingModule({ + imports: [RevisionsCustomStepComponent, MockComponents(CustomStepComponent)], providers: [ - MockProvider(ActivatedRoute, mockActivatedRoute), - MockProvider(Router, mockRouter), + provideOSFCore(), + provideActivatedRouteMock(mockRoute), + provideRouterMock(mockRouter), provideMockStore({ signals: [ { @@ -43,10 +45,11 @@ describe('RevisionsCustomStepComponent', () => { ], }), ], - }).compileComponents(); + }); fixture = TestBed.createComponent(RevisionsCustomStepComponent); component = fixture.componentInstance; + store = TestBed.inject(Store); fixture.detectChanges(); }); @@ -62,21 +65,23 @@ describe('RevisionsCustomStepComponent', () => { }); it('should dispatch updateRevision on onUpdateAction', () => { - const actionsMock = { updateRevision: jest.fn() } as any; - Object.defineProperty(component, 'actions', { value: actionsMock }); component.onUpdateAction({ x: 2 }); - expect(actionsMock.updateRevision).toHaveBeenCalledWith('rev-1', 'because', { x: 2 }); + expect(store.dispatch).toHaveBeenCalledWith(new UpdateSchemaResponse('rev-1', 'because', { x: 2 })); }); it('should navigate back to justification on onBack', () => { - const navSpy = jest.spyOn(TestBed.inject(Router), 'navigate'); component.onBack(); - expect(navSpy).toHaveBeenCalledWith(['../', 'justification'], { relativeTo: TestBed.inject(ActivatedRoute) }); + expect(mockRouter.navigate).toHaveBeenCalledWith( + ['../', 'justification'], + expect.objectContaining({ relativeTo: expect.anything() }) + ); }); it('should navigate to review on onNext', () => { - const navSpy = jest.spyOn(TestBed.inject(Router), 'navigate'); component.onNext(); - expect(navSpy).toHaveBeenCalledWith(['../', 'review'], { relativeTo: TestBed.inject(ActivatedRoute) }); + expect(mockRouter.navigate).toHaveBeenCalledWith( + ['../', 'review'], + expect.objectContaining({ relativeTo: expect.anything() }) + ); }); }); diff --git a/src/app/features/registries/pages/revisions-custom-step/revisions-custom-step.component.ts b/src/app/features/registries/pages/revisions-custom-step/revisions-custom-step.component.ts index e59a55ef7..73b1a1c83 100644 --- a/src/app/features/registries/pages/revisions-custom-step/revisions-custom-step.component.ts +++ b/src/app/features/registries/pages/revisions-custom-step/revisions-custom-step.component.ts @@ -14,31 +14,18 @@ import { RegistriesSelectors, UpdateSchemaResponse } from '../../store'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class RevisionsCustomStepComponent { + private readonly route = inject(ActivatedRoute); + private readonly router = inject(Router); + readonly schemaResponse = select(RegistriesSelectors.getSchemaResponse); readonly schemaResponseRevisionData = select(RegistriesSelectors.getSchemaResponseRevisionData); - private readonly route = inject(ActivatedRoute); - private readonly router = inject(Router); - actions = createDispatchMap({ - updateRevision: UpdateSchemaResponse, - }); - - filesLink = computed(() => { - return this.schemaResponse()?.filesLink || ' '; - }); - - provider = computed(() => { - return this.schemaResponse()?.registrationId || ''; - }); - - projectId = computed(() => { - return this.schemaResponse()?.registrationId || ''; - }); - - stepsData = computed(() => { - const schemaResponse = this.schemaResponse(); - return schemaResponse?.revisionResponses || {}; - }); + actions = createDispatchMap({ updateRevision: UpdateSchemaResponse }); + + filesLink = computed(() => this.schemaResponse()?.filesLink || ' '); + provider = computed(() => this.schemaResponse()?.registrationId || ''); + projectId = computed(() => this.schemaResponse()?.registrationId || ''); + stepsData = computed(() => this.schemaResponse()?.revisionResponses || {}); onUpdateAction(data: Record): void { const id: string = this.route.snapshot.params['id'] || ''; diff --git a/src/app/features/registries/store/handlers/projects.handlers.ts b/src/app/features/registries/store/handlers/projects.handlers.ts index 9738d8442..88562a02a 100644 --- a/src/app/features/registries/store/handlers/projects.handlers.ts +++ b/src/app/features/registries/store/handlers/projects.handlers.ts @@ -5,7 +5,7 @@ import { inject, Injectable } from '@angular/core'; import { handleSectionError } from '@osf/shared/helpers/state-error.handler'; import { ProjectsService } from '@osf/shared/services/projects.service'; -import { ProjectShortInfoModel } from '../../models'; +import { ProjectShortInfoModel } from '../../models/project-short-info.model'; import { REGISTRIES_STATE_DEFAULTS, RegistriesStateModel } from '../registries.model'; @Injectable() diff --git a/src/app/features/registries/store/registries.model.ts b/src/app/features/registries/store/registries.model.ts index f83ee5291..4542aaa96 100644 --- a/src/app/features/registries/store/registries.model.ts +++ b/src/app/features/registries/store/registries.model.ts @@ -11,7 +11,7 @@ import { ResourceModel } from '@osf/shared/models/search/resource.model'; import { AsyncStateModel } from '@osf/shared/models/store/async-state.model'; import { AsyncStateWithTotalCount } from '@osf/shared/models/store/async-state-with-total-count.model'; -import { ProjectShortInfoModel } from '../models'; +import { ProjectShortInfoModel } from '../models/project-short-info.model'; export interface RegistriesStateModel { providerSchemas: AsyncStateModel; diff --git a/src/app/features/registries/store/registries.selectors.ts b/src/app/features/registries/store/registries.selectors.ts index 3335b9191..e75242bf2 100644 --- a/src/app/features/registries/store/registries.selectors.ts +++ b/src/app/features/registries/store/registries.selectors.ts @@ -1,5 +1,6 @@ import { Selector } from '@ngxs/store'; +import { UserPermissions } from '@osf/shared/enums/user-permissions.enum'; import { FileModel } from '@osf/shared/models/files/file.model'; import { FileFolderModel } from '@osf/shared/models/files/file-folder.model'; import { LicenseModel } from '@osf/shared/models/license/license.model'; @@ -11,7 +12,7 @@ import { RegistrationCard } from '@osf/shared/models/registration/registration-c import { SchemaResponse } from '@osf/shared/models/registration/schema-response.model'; import { ResourceModel } from '@osf/shared/models/search/resource.model'; -import { ProjectShortInfoModel } from '../models'; +import { ProjectShortInfoModel } from '../models/project-short-info.model'; import { RegistriesStateModel } from './registries.model'; import { RegistriesState } from './registries.state'; @@ -52,6 +53,11 @@ export class RegistriesSelectors { return state.draftRegistration.data; } + @Selector([RegistriesState]) + static hasDraftAdminAccess(state: RegistriesStateModel): boolean { + return state.draftRegistration.data?.currentUserPermissions?.includes(UserPermissions.Admin) || false; + } + @Selector([RegistriesState]) static getRegistrationLoading(state: RegistriesStateModel): boolean { return state.draftRegistration.isLoading || state.draftRegistration.isSubmitting || state.pagesSchema.isLoading; diff --git a/src/app/features/registries/store/registries.state.ts b/src/app/features/registries/store/registries.state.ts index 6a8ae7120..d24602bbf 100644 --- a/src/app/features/registries/store/registries.state.ts +++ b/src/app/features/registries/store/registries.state.ts @@ -54,11 +54,11 @@ import { REGISTRIES_STATE_DEFAULTS, RegistriesStateModel } from './registries.mo }) @Injectable() export class RegistriesState { - searchService = inject(GlobalSearchService); - registriesService = inject(RegistriesService); private readonly environment = inject(ENVIRONMENT); private readonly store = inject(Store); + searchService = inject(GlobalSearchService); + registriesService = inject(RegistriesService); providersHandler = inject(ProvidersHandlers); projectsHandler = inject(ProjectsHandlers); licensesHandler = inject(LicensesHandlers); @@ -238,7 +238,7 @@ export class RegistriesState { }, }); }), - catchError((error) => handleSectionError(ctx, 'draftRegistration', error)) + catchError((error) => handleSectionError(ctx, 'registration', error)) ); } diff --git a/src/testing/mocks/dynamic-dialog-ref.mock.ts b/src/testing/mocks/dynamic-dialog-ref.mock.ts index 091508d9e..d503e736d 100644 --- a/src/testing/mocks/dynamic-dialog-ref.mock.ts +++ b/src/testing/mocks/dynamic-dialog-ref.mock.ts @@ -1,8 +1,21 @@ import { DynamicDialogRef } from 'primeng/dynamicdialog'; +import { Subject } from 'rxjs'; + export const DynamicDialogRefMock = { provide: DynamicDialogRef, useValue: { close: jest.fn(), }, }; + +export function provideDynamicDialogRefMock() { + return { + provide: DynamicDialogRef, + useFactory: () => ({ + close: jest.fn(), + destroy: jest.fn(), + onClose: new Subject(), + }), + }; +} diff --git a/src/testing/mocks/registries.mock.ts b/src/testing/mocks/registries.mock.ts index fb5debaa8..bd3a5a998 100644 --- a/src/testing/mocks/registries.mock.ts +++ b/src/testing/mocks/registries.mock.ts @@ -1,25 +1,45 @@ import { FieldType } from '@osf/shared/enums/field-type.enum'; +import { UserPermissions } from '@osf/shared/enums/user-permissions.enum'; +import { DraftRegistrationModel } from '@osf/shared/models/registration/draft-registration.model'; +import { PageSchema } from '@osf/shared/models/registration/page-schema.model'; +import { ProviderSchema } from '@osf/shared/models/registration/provider-schema.model'; -export const MOCK_REGISTRIES_PAGE = { +export const MOCK_REGISTRIES_PAGE: PageSchema = { id: 'page-1', title: 'Page 1', questions: [ - { responseKey: 'field1', fieldType: FieldType.Text, required: true }, - { responseKey: 'field2', fieldType: FieldType.Text, required: false }, + { id: 'q1', displayText: 'Field 1', responseKey: 'field1', fieldType: FieldType.Text, required: true }, + { id: 'q2', displayText: 'Field 2', responseKey: 'field2', fieldType: FieldType.Text, required: false }, ], -} as any; +}; -export const MOCK_STEPS_DATA = { field1: 'value1', field2: 'value2' } as any; +export const MOCK_REGISTRIES_PAGE_WITH_SECTIONS: PageSchema = { + id: 'page-2', + title: 'Page 2', + questions: [], + sections: [ + { + id: 'sec-1', + title: 'Section 1', + questions: [ + { id: 'q3', displayText: 'Field 3', responseKey: 'field3', fieldType: FieldType.Text, required: true }, + ], + }, + ], +}; + +export const MOCK_STEPS_DATA: Record = { field1: 'value1', field2: 'value2' }; -export const MOCK_PAGES_SCHEMA = [MOCK_REGISTRIES_PAGE]; +export const MOCK_PAGES_SCHEMA: PageSchema[] = [MOCK_REGISTRIES_PAGE]; -export const MOCK_DRAFT_REGISTRATION = { +export const MOCK_DRAFT_REGISTRATION: Partial = { id: 'draft-1', title: ' My Title ', description: ' Description ', - license: { id: 'mit' }, + license: { id: 'mit', options: null }, providerId: 'osf', - currentUserPermissions: ['admin'], -} as any; + currentUserPermissions: [UserPermissions.Admin], + registrationSchemaId: 'schema-1', +}; -export const MOCK_PROVIDER_SCHEMAS = [{ id: 'schema-1' }] as any; +export const MOCK_PROVIDER_SCHEMAS: ProviderSchema[] = [{ id: 'schema-1', name: 'Schema 1' }]; diff --git a/src/testing/osf.testing.provider.ts b/src/testing/osf.testing.provider.ts new file mode 100644 index 000000000..f3710e33a --- /dev/null +++ b/src/testing/osf.testing.provider.ts @@ -0,0 +1,48 @@ +import { TranslateModule } from '@ngx-translate/core'; + +import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'; +import { provideHttpClientTesting } from '@angular/common/http/testing'; +import { importProvidersFrom } from '@angular/core'; +import { provideNoopAnimations } from '@angular/platform-browser/animations'; + +import { provideDynamicDialogRefMock } from './mocks/dynamic-dialog-ref.mock'; +import { EnvironmentTokenMock } from './mocks/environment.token.mock'; +import { ToastServiceMock } from './mocks/toast.service.mock'; +import { TranslationServiceMock } from './mocks/translation.service.mock'; +import { provideActivatedRouteMock } from './providers/route-provider.mock'; +import { provideRouterMock } from './providers/router-provider.mock'; + +export function provideOSFCore() { + return [ + provideNoopAnimations(), + importProvidersFrom(TranslateModule.forRoot()), + TranslationServiceMock, + EnvironmentTokenMock, + ]; +} + +export function provideOSFHttp() { + return [provideHttpClient(withInterceptorsFromDi()), provideHttpClientTesting()]; +} + +export function provideOSFRouting() { + return [provideRouterMock(), provideActivatedRouteMock()]; +} + +export function provideOSFDialog() { + return [provideDynamicDialogRefMock()]; +} + +export function provideOSFToast() { + return [ToastServiceMock]; +} + +export function provideOSFTesting() { + return [ + ...provideOSFCore(), + ...provideOSFHttp(), + ...provideOSFRouting(), + ...provideOSFDialog(), + ...provideOSFToast(), + ]; +} diff --git a/src/testing/providers/loader-service.mock.ts b/src/testing/providers/loader-service.mock.ts index 3a76f2822..eb7d002dd 100644 --- a/src/testing/providers/loader-service.mock.ts +++ b/src/testing/providers/loader-service.mock.ts @@ -1,5 +1,7 @@ import { signal } from '@angular/core'; +import { LoaderService } from '@osf/shared/services/loader.service'; + export class LoaderServiceMock { private _isLoading = signal(false); readonly isLoading = this._isLoading.asReadonly(); @@ -7,3 +9,10 @@ export class LoaderServiceMock { show = jest.fn(() => this._isLoading.set(true)); hide = jest.fn(() => this._isLoading.set(false)); } + +export function provideLoaderServiceMock(mock?: LoaderServiceMock) { + return { + provide: LoaderService, + useFactory: () => mock ?? new LoaderServiceMock(), + }; +} diff --git a/src/testing/providers/route-provider.mock.ts b/src/testing/providers/route-provider.mock.ts index 53e8b3de0..739aea0b5 100644 --- a/src/testing/providers/route-provider.mock.ts +++ b/src/testing/providers/route-provider.mock.ts @@ -6,6 +6,7 @@ export class ActivatedRouteMockBuilder { private paramsObj: Record = {}; private queryParamsObj: Record = {}; private dataObj: Record = {}; + private firstChildBuilder: ActivatedRouteMockBuilder | null = null; private params$ = new BehaviorSubject>({}); private queryParams$ = new BehaviorSubject>({}); @@ -39,6 +40,12 @@ export class ActivatedRouteMockBuilder { return this; } + withFirstChild(configureFn: (builder: ActivatedRouteMockBuilder) => void): ActivatedRouteMockBuilder { + this.firstChildBuilder = new ActivatedRouteMockBuilder(); + configureFn(this.firstChildBuilder); + return this; + } + build(): Partial { const paramMap = { get: jest.fn((key: string) => this.paramsObj[key]), @@ -47,6 +54,8 @@ export class ActivatedRouteMockBuilder { keys: Object.keys(this.paramsObj), }; + const firstChild = this.firstChildBuilder ? this.firstChildBuilder.build() : null; + const route: Partial = { parent: { params: this.params$.asObservable(), @@ -59,7 +68,9 @@ export class ActivatedRouteMockBuilder { queryParams: this.queryParamsObj, data: this.dataObj, paramMap: paramMap, + firstChild: firstChild?.snapshot ?? null, } as any, + firstChild: firstChild as any, params: this.params$.asObservable(), queryParams: this.queryParams$.asObservable(), data: this.data$.asObservable(), @@ -87,3 +98,10 @@ export const ActivatedRouteMock = { return ActivatedRouteMockBuilder.create().withData(data); }, }; + +export function provideActivatedRouteMock(mock?: ReturnType) { + return { + provide: ActivatedRoute, + useFactory: () => mock ?? ActivatedRouteMockBuilder.create().build(), + }; +} diff --git a/src/testing/providers/router-provider.mock.ts b/src/testing/providers/router-provider.mock.ts index b13d86b59..be8268a33 100644 --- a/src/testing/providers/router-provider.mock.ts +++ b/src/testing/providers/router-provider.mock.ts @@ -60,3 +60,10 @@ export const RouterMock = { return RouterMockBuilder.create(); }, }; + +export function provideRouterMock(mock?: RouterMockType) { + return { + provide: Router, + useFactory: () => mock ?? RouterMockBuilder.create().build(), + }; +}