diff --git a/src/app/features/my-projects/my-projects.component.spec.ts b/src/app/features/my-projects/my-projects.component.spec.ts index d3d9da18f..5c1caaab4 100644 --- a/src/app/features/my-projects/my-projects.component.spec.ts +++ b/src/app/features/my-projects/my-projects.component.spec.ts @@ -48,12 +48,12 @@ describe('MyProjectsComponent', () => { { selector: MyResourcesSelectors.getTotalProjects, value: 0 }, { selector: MyResourcesSelectors.getTotalRegistrations, value: 0 }, { selector: MyResourcesSelectors.getTotalPreprints, value: 0 }, - { selector: MyResourcesSelectors.getTotalBookmarks, value: 0 }, + { selector: BookmarksSelectors.getBookmarksTotalCount, value: 0 }, { selector: BookmarksSelectors.getBookmarksCollectionId, value: null }, { selector: MyResourcesSelectors.getProjects, value: [] }, { selector: MyResourcesSelectors.getRegistrations, value: [] }, { selector: MyResourcesSelectors.getPreprints, value: [] }, - { selector: MyResourcesSelectors.getBookmarks, value: [] }, + { selector: BookmarksSelectors.getBookmarks, value: [] }, ], }), { provide: ActivatedRoute, useValue: mockActivatedRoute }, diff --git a/src/app/features/project/overview/components/overview-collections/overview-collections.component.spec.ts b/src/app/features/project/overview/components/overview-collections/overview-collections.component.spec.ts index 4809b1a72..3ac5256fb 100644 --- a/src/app/features/project/overview/components/overview-collections/overview-collections.component.spec.ts +++ b/src/app/features/project/overview/components/overview-collections/overview-collections.component.spec.ts @@ -1,7 +1,7 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { collectionFilterNames } from '@osf/features/collections/constants'; -import { CollectionSubmission } from '@osf/shared/models/collections/collections.models'; +import { CollectionSubmission } from '@osf/shared/models/collections/collections.model'; import { OverviewCollectionsComponent } from './overview-collections.component'; diff --git a/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.html b/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.html index 8a74c891e..9608fd083 100644 --- a/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.html +++ b/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.html @@ -10,13 +10,13 @@ class="w-12rem btn-full-width" [label]="'common.buttons.cancel' | translate" severity="info" - (click)="dialogRef.close()" + (onClick)="dialogRef.close()" /> diff --git a/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.spec.ts b/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.spec.ts index d3130fff6..afb73a74e 100644 --- a/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.spec.ts +++ b/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.spec.ts @@ -1,46 +1,42 @@ +import { Store } from '@ngxs/store'; + import { MockProvider } from 'ng-mocks'; import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog'; -import { of } from 'rxjs'; - import { ComponentFixture, TestBed } from '@angular/core/testing'; import { SchemaActionTrigger } from '@osf/features/registries/enums'; +import { HandleSchemaResponse } from '@osf/features/registries/store'; import { ConfirmContinueEditingDialogComponent } from './confirm-continue-editing-dialog.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; +import { provideDynamicDialogRefMock } from '@testing/mocks/dynamic-dialog-ref.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('ConfirmContinueEditingDialogComponent', () => { let component: ConfirmContinueEditingDialogComponent; let fixture: ComponentFixture; - let mockDialogRef: DynamicDialogRef; - let mockDialogConfig: jest.Mocked; + let store: Store; + let dialogRef: DynamicDialogRef; const MOCK_REVISION_ID = 'test-revision-id'; - beforeEach(async () => { - mockDialogRef = { - close: jest.fn(), - } as any; - - mockDialogConfig = { - data: { revisionId: MOCK_REVISION_ID }, - } as jest.Mocked; - - await TestBed.configureTestingModule({ - imports: [ConfirmContinueEditingDialogComponent, OSFTestingModule], + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ConfirmContinueEditingDialogComponent], providers: [ - MockProvider(DynamicDialogRef, mockDialogRef), - MockProvider(DynamicDialogConfig, mockDialogConfig), - provideMockStore({ - signals: [], - }), + provideOSFCore(), + provideDynamicDialogRefMock(), + // MockProvider(DynamicDialogRef), + MockProvider(DynamicDialogConfig, { data: { revisionId: MOCK_REVISION_ID } }), + provideMockStore(), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); + dialogRef = TestBed.inject(DynamicDialogRef); fixture = TestBed.createComponent(ConfirmContinueEditingDialogComponent); component = fixture.componentInstance; fixture.detectChanges(); @@ -54,87 +50,27 @@ describe('ConfirmContinueEditingDialogComponent', () => { expect(component.isSubmitting).toBe(false); }); - it('should submit with comment', () => { - const testComment = 'Test comment'; - component.form.patchValue({ comment: testComment }); - - const mockActions = { - handleSchemaResponse: jest.fn().mockReturnValue(of({})), - }; - - Object.defineProperty(component, 'actions', { - value: mockActions, - writable: true, - }); + it('should dispatch handleSchemaResponse with comment on submit', () => { + component.form.patchValue({ comment: 'Test comment' }); component.submit(); - expect(mockActions.handleSchemaResponse).toHaveBeenCalledWith( - MOCK_REVISION_ID, - SchemaActionTrigger.AdminReject, - testComment + expect(store.dispatch).toHaveBeenCalledWith( + new HandleSchemaResponse(MOCK_REVISION_ID, SchemaActionTrigger.AdminReject, 'Test comment') ); + expect(dialogRef.close).toHaveBeenCalledWith(true); }); - it('should submit with empty comment', () => { - const mockActions = { - handleSchemaResponse: jest.fn().mockReturnValue(of({})), - }; - - Object.defineProperty(component, 'actions', { - value: mockActions, - writable: true, - }); - + it('should dispatch handleSchemaResponse with empty comment on submit', () => { component.submit(); - expect(mockActions.handleSchemaResponse).toHaveBeenCalledWith( - MOCK_REVISION_ID, - SchemaActionTrigger.AdminReject, - '' + expect(store.dispatch).toHaveBeenCalledWith( + new HandleSchemaResponse(MOCK_REVISION_ID, SchemaActionTrigger.AdminReject, '') ); }); - it('should set isSubmitting to true when submitting', () => { - const mockActions = { - handleSchemaResponse: jest.fn().mockReturnValue(of({}).pipe()), - }; - - Object.defineProperty(component, 'actions', { - value: mockActions, - writable: true, - }); - - component.submit(); - expect(mockActions.handleSchemaResponse).toHaveBeenCalled(); - }); - it('should update comment value', () => { - const testComment = 'New comment'; - component.form.patchValue({ comment: testComment }); - - expect(component.form.get('comment')?.value).toBe(testComment); - }); - - it('should handle different revision IDs', () => { - const differentRevisionId = 'different-revision-id'; - (component as any).config.data = { revisionId: differentRevisionId } as any; - - const mockActions = { - handleSchemaResponse: jest.fn().mockReturnValue(of({})), - }; - - Object.defineProperty(component, 'actions', { - value: mockActions, - writable: true, - }); - - component.submit(); - - expect(mockActions.handleSchemaResponse).toHaveBeenCalledWith( - differentRevisionId, - SchemaActionTrigger.AdminReject, - '' - ); + component.form.patchValue({ comment: 'New comment' }); + expect(component.form.get('comment')?.value).toBe('New comment'); }); }); diff --git a/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.ts b/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.ts index 87b307f68..b24087d4e 100644 --- a/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.ts +++ b/src/app/features/registries/components/confirm-continue-editing-dialog/confirm-continue-editing-dialog.component.ts @@ -23,20 +23,16 @@ import { HandleSchemaResponse } from '../../store'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class ConfirmContinueEditingDialogComponent { - readonly dialogRef = inject(DynamicDialogRef); - private readonly fb = inject(FormBuilder); readonly config = inject(DynamicDialogConfig); - private readonly destroyRef = inject(DestroyRef); + readonly dialogRef = inject(DynamicDialogRef); + readonly destroyRef = inject(DestroyRef); + readonly fb = inject(FormBuilder); - actions = createDispatchMap({ - handleSchemaResponse: HandleSchemaResponse, - }); + actions = createDispatchMap({ handleSchemaResponse: HandleSchemaResponse }); isSubmitting = false; - form: FormGroup = this.fb.group({ - comment: [''], - }); + form: FormGroup = this.fb.group({ comment: [''] }); submit(): void { const comment = this.form.value.comment; diff --git a/src/app/features/registries/components/confirm-registration-dialog/confirm-registration-dialog.component.spec.ts b/src/app/features/registries/components/confirm-registration-dialog/confirm-registration-dialog.component.spec.ts index 3cd46f5fb..781dbc459 100644 --- a/src/app/features/registries/components/confirm-registration-dialog/confirm-registration-dialog.component.spec.ts +++ b/src/app/features/registries/components/confirm-registration-dialog/confirm-registration-dialog.component.spec.ts @@ -1,47 +1,50 @@ +import { Store } from '@ngxs/store'; + import { MockProvider } from 'ng-mocks'; import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog'; -import { of } from 'rxjs'; +import { throwError } from 'rxjs'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { SubmitType } from '@osf/features/registries/enums'; -import { RegistriesSelectors } from '@osf/features/registries/store'; +import { RegisterDraft, RegistriesSelectors } from '@osf/features/registries/store'; import { ConfirmRegistrationDialogComponent } from './confirm-registration-dialog.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; +import { provideDynamicDialogRefMock } from '@testing/mocks/dynamic-dialog-ref.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('ConfirmRegistrationDialogComponent', () => { let component: ConfirmRegistrationDialogComponent; let fixture: ComponentFixture; - let mockDialogRef: DynamicDialogRef; - let mockDialogConfig: jest.Mocked; + let store: Store; + let dialogRef: DynamicDialogRef; const MOCK_CONFIG_DATA = { draftId: 'draft-1', providerId: 'provider-1', projectId: 'project-1', - components: [], + components: [] as string[], }; - beforeEach(async () => { - mockDialogRef = { close: jest.fn() } as any; - mockDialogConfig = { data: { ...MOCK_CONFIG_DATA } } as any; - - await TestBed.configureTestingModule({ - imports: [ConfirmRegistrationDialogComponent, OSFTestingModule], + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ConfirmRegistrationDialogComponent], providers: [ - MockProvider(DynamicDialogRef, mockDialogRef), - MockProvider(DynamicDialogConfig, mockDialogConfig), + provideOSFCore(), + provideDynamicDialogRefMock(), + MockProvider(DynamicDialogConfig, { data: { ...MOCK_CONFIG_DATA } }), provideMockStore({ signals: [{ selector: RegistriesSelectors.isRegistrationSubmitting, value: false }], }), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); + dialogRef = TestBed.inject(DynamicDialogRef); fixture = TestBed.createComponent(ConfirmRegistrationDialogComponent); component = fixture.componentInstance; fixture.detectChanges(); @@ -78,44 +81,60 @@ describe('ConfirmRegistrationDialogComponent', () => { expect(embargoControl?.value).toBeNull(); }); - it('should submit with immediate option and close dialog', () => { - const mockActions = { - registerDraft: jest.fn().mockReturnValue(of({})), - }; - Object.defineProperty(component, 'actions', { value: mockActions, writable: true }); - + it('should dispatch registerDraft with immediate option and close dialog', () => { component.form.get('submitOption')?.setValue(SubmitType.Public); + component.submit(); - expect(mockActions.registerDraft).toHaveBeenCalledWith( - MOCK_CONFIG_DATA.draftId, - '', - MOCK_CONFIG_DATA.providerId, - MOCK_CONFIG_DATA.projectId, - MOCK_CONFIG_DATA.components + expect(store.dispatch).toHaveBeenCalledWith( + new RegisterDraft( + MOCK_CONFIG_DATA.draftId, + '', + MOCK_CONFIG_DATA.providerId, + MOCK_CONFIG_DATA.projectId, + MOCK_CONFIG_DATA.components + ) ); - expect(mockDialogRef.close).toHaveBeenCalledWith(true); + expect(dialogRef.close).toHaveBeenCalledWith(true); }); - it('should submit with embargo and include ISO embargoDate', () => { - const mockActions = { - registerDraft: jest.fn().mockReturnValue(of({})), - }; - Object.defineProperty(component, 'actions', { value: mockActions, writable: true }); - + it('should dispatch registerDraft with embargo and include ISO embargoDate', () => { const date = new Date('2025-01-01T00:00:00Z'); component.form.get('submitOption')?.setValue(SubmitType.Embargo); component.form.get('embargoDate')?.setValue(date); component.submit(); - expect(mockActions.registerDraft).toHaveBeenCalledWith( - MOCK_CONFIG_DATA.draftId, - date.toISOString(), - MOCK_CONFIG_DATA.providerId, - MOCK_CONFIG_DATA.projectId, - MOCK_CONFIG_DATA.components + expect(store.dispatch).toHaveBeenCalledWith( + new RegisterDraft( + MOCK_CONFIG_DATA.draftId, + date.toISOString(), + MOCK_CONFIG_DATA.providerId, + MOCK_CONFIG_DATA.projectId, + MOCK_CONFIG_DATA.components + ) ); - expect(mockDialogRef.close).toHaveBeenCalledWith(true); + expect(dialogRef.close).toHaveBeenCalledWith(true); + }); + + it('should return a date 3 days in the future for minEmbargoDate', () => { + const expected = new Date(); + expected.setDate(expected.getDate() + 3); + + const result = component.minEmbargoDate(); + + expect(result.getFullYear()).toBe(expected.getFullYear()); + expect(result.getMonth()).toBe(expected.getMonth()); + expect(result.getDate()).toBe(expected.getDate()); + }); + + it('should re-enable form on submit error', () => { + (store.dispatch as jest.Mock).mockReturnValueOnce(throwError(() => new Error('fail'))); + + component.form.get('submitOption')?.setValue(SubmitType.Public); + component.submit(); + + expect(component.form.enabled).toBe(true); + expect(dialogRef.close).not.toHaveBeenCalled(); }); }); diff --git a/src/app/features/registries/components/confirm-registration-dialog/confirm-registration-dialog.component.ts b/src/app/features/registries/components/confirm-registration-dialog/confirm-registration-dialog.component.ts index 874b1896f..56ee36981 100644 --- a/src/app/features/registries/components/confirm-registration-dialog/confirm-registration-dialog.component.ts +++ b/src/app/features/registries/components/confirm-registration-dialog/confirm-registration-dialog.component.ts @@ -7,7 +7,8 @@ import { DatePicker } from 'primeng/datepicker'; import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog'; import { RadioButton } from 'primeng/radiobutton'; -import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core'; +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; import { SubmitType } from '../../enums'; @@ -21,14 +22,13 @@ import { RegisterDraft, RegistriesSelectors } from '../../store'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class ConfirmRegistrationDialogComponent { - readonly dialogRef = inject(DynamicDialogRef); - private readonly fb = inject(FormBuilder); readonly config = inject(DynamicDialogConfig); + readonly dialogRef = inject(DynamicDialogRef); + readonly destroyRef = inject(DestroyRef); + readonly fb = inject(FormBuilder); readonly isRegistrationSubmitting = select(RegistriesSelectors.isRegistrationSubmitting); - actions = createDispatchMap({ - registerDraft: RegisterDraft, - }); + actions = createDispatchMap({ registerDraft: RegisterDraft }); SubmitType = SubmitType; showDateControl = false; minEmbargoDate = computed(() => { @@ -43,21 +43,24 @@ export class ConfirmRegistrationDialogComponent { }); constructor() { - this.form.get('submitOption')!.valueChanges.subscribe((value) => { - this.showDateControl = value === SubmitType.Embargo; - const dateControl = this.form.get('embargoDate'); + this.form + .get('submitOption') + ?.valueChanges.pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((value) => { + this.showDateControl = value === SubmitType.Embargo; + const dateControl = this.form.get('embargoDate'); - if (this.showDateControl) { - dateControl!.enable(); - dateControl!.setValidators(Validators.required); - } else { - dateControl!.disable(); - dateControl!.clearValidators(); - dateControl!.reset(); - } + if (this.showDateControl) { + dateControl!.enable(); + dateControl!.setValidators(Validators.required); + } else { + dateControl!.disable(); + dateControl!.clearValidators(); + dateControl!.reset(); + } - dateControl!.updateValueAndValidity(); - }); + dateControl!.updateValueAndValidity(); + }); } submit(): void { diff --git a/src/app/features/registries/components/custom-step/custom-step.component.spec.ts b/src/app/features/registries/components/custom-step/custom-step.component.spec.ts index 1b287987e..a354ad6b6 100644 --- a/src/app/features/registries/components/custom-step/custom-step.component.spec.ts +++ b/src/app/features/registries/components/custom-step/custom-step.component.spec.ts @@ -1,50 +1,92 @@ +import { Store } from '@ngxs/store'; + import { MockComponents, MockProvider } from 'ng-mocks'; +import { signal, WritableSignal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { FormGroup } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { InfoIconComponent } from '@osf/shared/components/info-icon/info-icon.component'; +import { FieldType } from '@osf/shared/enums/field-type.enum'; +import { ToastService } from '@osf/shared/services/toast.service'; +import { FileModel } from '@shared/models/files/file.model'; +import { FilePayloadJsonApi } from '@shared/models/files/file-payload-json-api.model'; +import { PageSchema } from '@shared/models/registration/page-schema.model'; -import { RegistriesSelectors } from '../../store'; +import { RegistriesSelectors, SetUpdatedFields, UpdateStepState } from '../../store'; import { FilesControlComponent } from '../files-control/files-control.component'; import { CustomStepComponent } from './custom-step.component'; import { MOCK_REGISTRIES_PAGE, MOCK_STEPS_DATA } from '@testing/mocks/registries.mock'; -import { OSFTestingModule } from '@testing/osf.testing.module'; +import { provideOSFCore } from '@testing/osf.testing.provider'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; -import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; +import { ToastServiceMock, ToastServiceMockType } from '@testing/providers/toast-provider.mock'; + +type StepsState = Record; describe('CustomStepComponent', () => { let component: CustomStepComponent; let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; - let mockRouter: ReturnType; + let store: Store; + let routeBuilder: ActivatedRouteMockBuilder; + let mockRouter: RouterMockType; + let toastMock: ToastServiceMockType; + let pagesSignal: WritableSignal; + let stepsStateSignal: WritableSignal; - const MOCK_PAGE = MOCK_REGISTRIES_PAGE; + function createComponent( + page: PageSchema, + stepsData: Record = {}, + stepsState: StepsState = {} + ): ComponentFixture { + pagesSignal.set([page]); + stepsStateSignal.set(stepsState); + const f = TestBed.createComponent(CustomStepComponent); + f.componentRef.setInput('stepsData', stepsData); + f.componentRef.setInput('filesLink', 'files-link'); + f.componentRef.setInput('projectId', 'project'); + f.componentRef.setInput('provider', 'provider'); + f.detectChanges(); + return f; + } - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ step: 1 }).build(); + function createPage( + questions: PageSchema['questions'] = [], + sections: PageSchema['sections'] = undefined + ): PageSchema { + return { id: 'p', title: 'P', questions, sections }; + } + + beforeEach(() => { + toastMock = ToastServiceMock.simple(); + routeBuilder = ActivatedRouteMockBuilder.create().withParams({ step: 1 }); mockRouter = RouterMockBuilder.create().withUrl('/registries/drafts/id/1').build(); + pagesSignal = signal([MOCK_REGISTRIES_PAGE]); + stepsStateSignal = signal({}); - await TestBed.configureTestingModule({ - imports: [CustomStepComponent, OSFTestingModule, ...MockComponents(InfoIconComponent, FilesControlComponent)], + TestBed.configureTestingModule({ + imports: [CustomStepComponent, ...MockComponents(InfoIconComponent, FilesControlComponent)], providers: [ - MockProvider(ActivatedRoute, mockActivatedRoute), + provideOSFCore(), + MockProvider(ToastService, toastMock), + MockProvider(ActivatedRoute, routeBuilder.build()), MockProvider(Router, mockRouter), provideMockStore({ signals: [ - { selector: RegistriesSelectors.getPagesSchema, value: [MOCK_PAGE] }, - { selector: RegistriesSelectors.getStepsState, value: {} }, + { selector: RegistriesSelectors.getPagesSchema, value: pagesSignal }, + { selector: RegistriesSelectors.getStepsState, value: stepsStateSignal }, ], }), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(CustomStepComponent); component = fixture.componentInstance; - fixture.componentRef.setInput('stepsData', MOCK_STEPS_DATA); fixture.componentRef.setInput('filesLink', 'files-link'); fixture.componentRef.setInput('projectId', 'project'); @@ -57,20 +99,200 @@ describe('CustomStepComponent', () => { }); it('should initialize stepForm when page available', () => { - expect(component['stepForm']).toBeDefined(); expect(Object.keys(component['stepForm'].controls)).toContain('field1'); expect(Object.keys(component['stepForm'].controls)).toContain('field2'); }); - it('should navigate back when goBack called on first step', () => { + it('should emit back on first step', () => { const backSpy = jest.spyOn(component.back, 'emit'); component.goBack(); expect(backSpy).toHaveBeenCalled(); }); - it('should navigate next when goNext called with within pages', () => { - Object.defineProperty(component, 'pages', { value: () => [MOCK_REGISTRIES_PAGE, MOCK_REGISTRIES_PAGE] }); + it('should navigate to previous step on step > 1', () => { + component.step.set(2); + component.goBack(); + expect(mockRouter.navigate).toHaveBeenCalledWith(['../', 1], { relativeTo: expect.anything() }); + }); + + it('should navigate to next step within pages', () => { + pagesSignal.set([MOCK_REGISTRIES_PAGE, MOCK_REGISTRIES_PAGE]); component.goNext(); - expect(mockRouter.navigate).toHaveBeenCalled(); + expect(mockRouter.navigate).toHaveBeenCalledWith(['../', 2], { relativeTo: expect.anything() }); + }); + + it('should emit next on last step', () => { + const nextSpy = jest.spyOn(component.next, 'emit'); + component.step.set(1); + component.goNext(); + expect(nextSpy).toHaveBeenCalled(); + }); + + it('should dispatch updateStepState on ngOnDestroy', () => { + (store.dispatch as jest.Mock).mockClear(); + component.ngOnDestroy(); + expect(store.dispatch).toHaveBeenCalledWith(expect.any(UpdateStepState)); + }); + + it('should emit updateAction and dispatch setUpdatedFields when fields changed', () => { + const emitSpy = jest.spyOn(component.updateAction, 'emit'); + component['stepForm'].get('field1')?.setValue('changed'); + (store.dispatch as jest.Mock).mockClear(); + + component.ngOnDestroy(); + + expect(emitSpy).toHaveBeenCalled(); + expect(store.dispatch).toHaveBeenCalledWith(new SetUpdatedFields({ field1: 'changed' })); + }); + + it('should not emit updateAction when no fields changed', () => { + const emitSpy = jest.spyOn(component.updateAction, 'emit'); + (store.dispatch as jest.Mock).mockClear(); + + component.ngOnDestroy(); + + expect(emitSpy).not.toHaveBeenCalled(); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(SetUpdatedFields)); + }); + + it('should skip saveStepState when form has no controls', () => { + component.stepForm = new FormGroup({}); + (store.dispatch as jest.Mock).mockClear(); + + component.ngOnDestroy(); + + expect(store.dispatch).not.toHaveBeenCalled(); + }); + + it('should attach file and emit updateAction', () => { + const emitSpy = jest.spyOn(component.updateAction, 'emit'); + const mockFile = { + id: 'new-file', + name: 'new.txt', + links: { html: 'http://html', download: 'http://dl' }, + extra: { hashes: { sha256: 'abc' } }, + } as FileModel; + + component.onAttachFile(mockFile, 'field1'); + + expect(component.attachedFiles['field1'].length).toBe(1); + expect(emitSpy).toHaveBeenCalled(); + expect(emitSpy.mock.calls[0][0]['field1'][0].file_id).toBe('new-file'); + }); + + it('should not attach duplicate file', () => { + component.attachedFiles['field1'] = [{ file_id: 'file-1', name: 'existing.txt' }]; + const emitSpy = jest.spyOn(component.updateAction, 'emit'); + + component.onAttachFile({ id: 'file-1' } as FileModel, 'field1'); + + expect(component.attachedFiles['field1'].length).toBe(1); + expect(emitSpy).not.toHaveBeenCalled(); + }); + + it('should show warning when attachment limit reached', () => { + component.attachedFiles['field1'] = Array.from({ length: 5 }, (_, i) => ({ file_id: `f-${i}`, name: `f-${i}` })); + + const mockFile = { + id: 'new', + name: 'new.txt', + links: { html: '', download: '' }, + extra: { hashes: { sha256: '', md5: '' } }, + } as FileModel; + component.onAttachFile(mockFile, 'field1'); + + expect(toastMock.showWarn).toHaveBeenCalledWith('shared.files.limitText'); + expect(component.attachedFiles['field1'].length).toBe(5); + }); + + it('should remove file and emit updateAction', () => { + const emitSpy = jest.spyOn(component.updateAction, 'emit'); + component.attachedFiles['field1'] = [ + { file_id: 'f1', name: 'a' }, + { file_id: 'f2', name: 'b' }, + ]; + + component.removeFromAttachedFiles({ file_id: 'f1', name: 'a' }, 'field1'); + + expect(component.attachedFiles['field1'].length).toBe(1); + expect(component.attachedFiles['field1'][0].file_id).toBe('f2'); + expect(emitSpy).toHaveBeenCalled(); + }); + + it('should skip non-existent questionKey', () => { + const emitSpy = jest.spyOn(component.updateAction, 'emit'); + component.removeFromAttachedFiles({ file_id: 'f1' }, 'nonexistent'); + expect(emitSpy).not.toHaveBeenCalled(); + }); + + it('should save step state and update step on route param change', () => { + (store.dispatch as jest.Mock).mockClear(); + routeBuilder.withParams({ step: 2 }); + + expect(store.dispatch).toHaveBeenCalledWith(expect.any(UpdateStepState)); + expect(component.step()).toBe(2); + }); + + it('should mark form touched when stepsState has invalid for current step', () => { + const f = createComponent(MOCK_REGISTRIES_PAGE, MOCK_STEPS_DATA, { + 1: { invalid: true, touched: true }, + }); + expect(f.componentInstance['stepForm'].get('field1')?.touched).toBe(true); + }); + + it('should initialize checkbox control with empty array default', () => { + const page = createPage([ + { id: 'q', displayText: '', responseKey: 'cbField', fieldType: FieldType.Checkbox, required: true }, + ]); + const f = createComponent(page); + expect(f.componentInstance['stepForm'].get('cbField')?.value).toEqual([]); + }); + + it('should initialize radio control with required validator', () => { + const page = createPage([ + { id: 'q', displayText: '', responseKey: 'radioField', fieldType: FieldType.Radio, required: true }, + ]); + const f = createComponent(page); + expect(f.componentInstance['stepForm'].get('radioField')?.valid).toBe(false); + }); + + it('should initialize file control and populate attachedFiles', () => { + const page = createPage([ + { id: 'q', displayText: '', responseKey: 'fileField', fieldType: FieldType.File, required: false }, + ]); + const files: FilePayloadJsonApi[] = [ + { file_id: 'f1', file_name: 'doc.pdf', file_urls: { html: '', download: '' }, file_hashes: { sha256: '' } }, + ]; + const f = createComponent(page, { fileField: files }); + + expect(f.componentInstance.attachedFiles['fileField'].length).toBe(1); + expect(f.componentInstance.attachedFiles['fileField'][0].name).toBe('doc.pdf'); + }); + + it('should skip unknown field types', () => { + const page = createPage([ + { id: 'q', displayText: '', responseKey: 'unknownField', fieldType: 'unknown' as FieldType, required: false }, + ]); + const f = createComponent(page); + expect(f.componentInstance['stepForm'].get('unknownField')).toBeNull(); + }); + + it('should include section questions', () => { + const page = createPage( + [], + [ + { + id: 's1', + title: 'S', + questions: [ + { id: 'q', displayText: '', responseKey: 'secField', fieldType: FieldType.Text, required: false }, + ], + }, + ] + ); + const f = createComponent(page, { secField: 'val' }); + + expect(f.componentInstance['stepForm'].get('secField')).toBeDefined(); + expect(f.componentInstance['stepForm'].get('secField')?.value).toBe('val'); }); }); diff --git a/src/app/features/registries/components/custom-step/custom-step.component.ts b/src/app/features/registries/components/custom-step/custom-step.component.ts index 98900e02c..357bc71b5 100644 --- a/src/app/features/registries/components/custom-step/custom-step.component.ts +++ b/src/app/features/registries/components/custom-step/custom-step.component.ts @@ -26,7 +26,7 @@ import { signal, } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { FormBuilder, FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; +import { FormBuilder, FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { InfoIconComponent } from '@osf/shared/components/info-icon/info-icon.component'; @@ -41,28 +41,27 @@ import { FilePayloadJsonApi } from '@shared/models/files/file-payload-json-api.m import { PageSchema } from '@shared/models/registration/page-schema.model'; import { FilesMapper } from '../../mappers/files.mapper'; +import { AttachedFile } from '../../models/attached-file.model'; import { RegistriesSelectors, SetUpdatedFields, UpdateStepState } from '../../store'; import { FilesControlComponent } from '../files-control/files-control.component'; @Component({ selector: 'osf-custom-step', imports: [ + Button, Card, - Textarea, - RadioButton, - FormsModule, Checkbox, - TranslatePipe, + Chip, + Inplace, InputText, + Message, + RadioButton, + Textarea, + ReactiveFormsModule, NgTemplateOutlet, - Inplace, - TranslatePipe, InfoIconComponent, - Button, - ReactiveFormsModule, - Message, FilesControlComponent, - Chip, + TranslatePipe, ], templateUrl: './custom-step.component.html', styleUrl: './custom-step.component.scss', @@ -80,38 +79,100 @@ export class CustomStepComponent implements OnDestroy { updateAction = output>(); back = output(); next = output(); + private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); private readonly fb = inject(FormBuilder); private readonly destroyRef = inject(DestroyRef); - private toastService = inject(ToastService); + private readonly toastService = inject(ToastService); readonly pages = select(RegistriesSelectors.getPagesSchema); - readonly FieldType = FieldType; readonly stepsState = select(RegistriesSelectors.getStepsState); - readonly actions = createDispatchMap({ + private readonly actions = createDispatchMap({ updateStepState: UpdateStepState, setUpdatedFields: SetUpdatedFields, }); + readonly FieldType = FieldType; readonly INPUT_VALIDATION_MESSAGES = INPUT_VALIDATION_MESSAGES; step = signal(this.route.snapshot.params['step']); currentPage = computed(() => this.pages()[this.step() - 1]); - radio = null; + stepForm: FormGroup = this.fb.group({}); + attachedFiles: Record = {}; - stepForm!: FormGroup; + constructor() { + this.setupRouteWatcher(); + this.setupPageFormInit(); + } - attachedFiles: Record[]> = {}; + ngOnDestroy(): void { + this.saveStepState(); + } - constructor() { + onAttachFile(file: FileModel, questionKey: string): void { + this.attachedFiles[questionKey] = this.attachedFiles[questionKey] || []; + + if (this.attachedFiles[questionKey].some((f) => f.file_id === file.id)) { + return; + } + + if (this.attachedFiles[questionKey].length >= FILE_COUNT_ATTACHMENTS_LIMIT) { + this.toastService.showWarn('shared.files.limitText'); + return; + } + + this.attachedFiles[questionKey] = [...this.attachedFiles[questionKey], file]; + this.stepForm.patchValue({ [questionKey]: this.attachedFiles[questionKey] }); + + const otherFormValues = { ...this.stepForm.value }; + delete otherFormValues[questionKey]; + this.updateAction.emit({ + [questionKey]: this.mapFilesToPayload(this.attachedFiles[questionKey]), + ...otherFormValues, + }); + } + + removeFromAttachedFiles(file: AttachedFile, questionKey: string): void { + if (!this.attachedFiles[questionKey]) { + return; + } + + this.attachedFiles[questionKey] = this.attachedFiles[questionKey].filter((f) => f.file_id !== file.file_id); + this.stepForm.patchValue({ [questionKey]: this.attachedFiles[questionKey] }); + this.updateAction.emit({ + [questionKey]: this.mapFilesToPayload(this.attachedFiles[questionKey]), + }); + } + + goBack(): void { + const previousStep = this.step() - 1; + if (previousStep > 0) { + this.router.navigate(['../', previousStep], { relativeTo: this.route }); + } else { + this.back.emit(); + } + } + + goNext(): void { + const nextStep = this.step() + 1; + if (nextStep <= this.pages().length) { + this.router.navigate(['../', nextStep], { relativeTo: this.route }); + } else { + this.next.emit(); + } + } + + private setupRouteWatcher() { this.route.params.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => { - this.updateStepState(); + this.saveStepState(); this.step.set(+params['step']); }); + } + private setupPageFormInit() { effect(() => { const page = this.currentPage(); if (page) { @@ -122,138 +183,78 @@ export class CustomStepComponent implements OnDestroy { private initStepForm(page: PageSchema): void { this.stepForm = this.fb.group({}); - let questions = page.questions || []; - if (page.sections?.length) { - questions = [...questions, ...page.sections.flatMap((section) => section.questions ?? [])]; - } - questions?.forEach((q) => { + const questions = [ + ...(page.questions || []), + ...(page.sections?.flatMap((section) => section.questions ?? []) ?? []), + ]; + + questions.forEach((q) => { const controlName = q.responseKey as string; - let control: FormControl; - - switch (q.fieldType) { - case FieldType.Text: - case FieldType.TextArea: - control = this.fb.control(this.stepsData()[controlName], { - validators: q.required ? [CustomValidators.requiredTrimmed()] : [], - }); - break; - - case FieldType.Checkbox: - control = this.fb.control(this.stepsData()[controlName] || [], { - validators: q.required ? [Validators.required] : [], - }); - break; - - case FieldType.Radio: - case FieldType.Select: - control = this.fb.control(this.stepsData()[controlName], { - validators: q.required ? [Validators.required] : [], - }); - break; - - case FieldType.File: - control = this.fb.control(this.stepsData()[controlName] || [], { - validators: q.required ? [Validators.required] : [], - }); - this.attachedFiles[controlName] = - this.stepsData()[controlName]?.map((file: FilePayloadJsonApi) => ({ ...file, name: file.file_name })) || []; - break; - - default: - return; + const control = this.createControl(q.fieldType!, controlName, q.required); + if (!control) return; + + if (q.fieldType === FieldType.File) { + this.attachedFiles[controlName] = + this.stepsData()[controlName]?.map((file: FilePayloadJsonApi) => ({ ...file, name: file.file_name })) || []; } this.stepForm.addControl(controlName, control); }); + if (this.stepsState()?.[this.step()]?.invalid) { this.stepForm.markAllAsTouched(); } } - private updateDraft() { - const changedFields = findChangedFields(this.stepForm.value, this.stepsData()); - if (Object.keys(changedFields).length > 0) { - this.actions.setUpdatedFields(changedFields); - this.updateAction.emit(this.stepForm.value); - } - } + private createControl(fieldType: FieldType, controlName: string, required: boolean): FormControl | null { + const value = this.stepsData()[controlName]; - private updateStepState() { - if (this.stepForm) { - this.updateDraft(); - this.stepForm.markAllAsTouched(); - this.actions.updateStepState(this.step(), this.stepForm.invalid, true); - } - } + switch (fieldType) { + case FieldType.Text: + case FieldType.TextArea: + return this.fb.control(value, { + validators: required ? [CustomValidators.requiredTrimmed()] : [], + }); - onAttachFile(file: FileModel, questionKey: string): void { - this.attachedFiles[questionKey] = this.attachedFiles[questionKey] || []; + case FieldType.Checkbox: + case FieldType.File: + return this.fb.control(value || [], { + validators: required ? [Validators.required] : [], + }); - if (!this.attachedFiles[questionKey].some((f) => f.file_id === file.id)) { - if (this.attachedFiles[questionKey].length >= FILE_COUNT_ATTACHMENTS_LIMIT) { - this.toastService.showWarn('shared.files.limitText'); - return; - } - this.attachedFiles[questionKey].push(file); - this.stepForm.patchValue({ - [questionKey]: [...(this.attachedFiles[questionKey] || []), file], - }); - const otherFormValues = { ...this.stepForm.value }; - delete otherFormValues[questionKey]; - this.updateAction.emit({ - [questionKey]: [ - ...this.attachedFiles[questionKey].map((f) => { - if (f.file_id) { - const { name: _, ...payload } = f; - return payload; - } - return FilesMapper.toFilePayload(f as FileModel); - }), - ], - ...otherFormValues, - }); - } - } + case FieldType.Radio: + case FieldType.Select: + return this.fb.control(value, { + validators: required ? [Validators.required] : [], + }); - removeFromAttachedFiles(file: Partial, questionKey: string): void { - if (this.attachedFiles[questionKey]) { - this.attachedFiles[questionKey] = this.attachedFiles[questionKey].filter((f) => f.file_id !== file.file_id); - this.stepForm.patchValue({ - [questionKey]: this.attachedFiles[questionKey], - }); - this.updateAction.emit({ - [questionKey]: [ - ...this.attachedFiles[questionKey].map((f) => { - if (f.file_id) { - const { name: _, ...payload } = f; - return payload; - } - return FilesMapper.toFilePayload(f as FileModel); - }), - ], - }); + default: + return null; } } - goBack(): void { - const previousStep = this.step() - 1; - if (previousStep > 0) { - this.router.navigate(['../', previousStep], { relativeTo: this.route }); - } else { - this.back.emit(); + private saveStepState() { + if (!this.stepForm.controls || !Object.keys(this.stepForm.controls).length) { + return; } - } - goNext(): void { - const nextStep = this.step() + 1; - if (nextStep <= this.pages().length) { - this.router.navigate(['../', nextStep], { relativeTo: this.route }); - } else { - this.next.emit(); + const changedFields = findChangedFields(this.stepForm.value, this.stepsData()); + if (Object.keys(changedFields).length > 0) { + this.actions.setUpdatedFields(changedFields); + this.updateAction.emit(this.stepForm.value); } + + this.stepForm.markAllAsTouched(); + this.actions.updateStepState(this.step(), this.stepForm.invalid, true); } - ngOnDestroy(): void { - this.updateStepState(); + private mapFilesToPayload(files: AttachedFile[]): FilePayloadJsonApi[] { + return files.map((f) => { + if (f.file_id) { + const { name: _, ...payload } = f; + return payload as FilePayloadJsonApi; + } + return FilesMapper.toFilePayload(f as FileModel); + }); } } diff --git a/src/app/features/registries/components/drafts/drafts.component.spec.ts b/src/app/features/registries/components/drafts/drafts.component.spec.ts index 98221ba90..7325770a2 100644 --- a/src/app/features/registries/components/drafts/drafts.component.spec.ts +++ b/src/app/features/registries/components/drafts/drafts.component.spec.ts @@ -1,76 +1,452 @@ +import { Store } from '@ngxs/store'; + import { MockComponents, MockProvider } from 'ng-mocks'; import { of } from 'rxjs'; -import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; 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 { ContributorsSelectors } from '@osf/shared/stores/contributors'; import { SubjectsSelectors } from '@osf/shared/stores/subjects'; -import { RegistriesSelectors } from '../../store'; +import { ClearState, RegistriesSelectors } from '../../store'; import { DraftsComponent } from './drafts.component'; -import { MOCK_DRAFT_REGISTRATION, MOCK_PAGES_SCHEMA } from '@testing/mocks/registries.mock'; -import { OSFTestingModule } from '@testing/osf.testing.module'; +import { + MOCK_DRAFT_REGISTRATION, + MOCK_PAGES_SCHEMA, + MOCK_REGISTRIES_PAGE_WITH_SECTIONS, + MOCK_STEPS_DATA, +} from '@testing/mocks/registries.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; +import { LoaderServiceMock } from '@testing/providers/loader-service.mock'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; -import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; -describe('DraftsComponent', () => { - let component: DraftsComponent; - let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; - let mockRouter: ReturnType; +interface SetupOverrides { + routeParams?: Record; + firstChildParams?: Record | null; + routerUrl?: string; + routerEvents?: unknown; + selectorOverrides?: { selector: unknown; value: unknown }[]; +} - const MOCK_PAGES = MOCK_PAGES_SCHEMA; - const MOCK_DRAFT = MOCK_DRAFT_REGISTRATION; +function setup(overrides: SetupOverrides = {}) { + const routeBuilder = ActivatedRouteMockBuilder.create().withParams(overrides.routeParams ?? { id: 'reg-1' }); + const mockActivatedRoute = routeBuilder.build(); - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'reg-1' }).build(); - mockRouter = RouterMockBuilder.create().withUrl('/registries/drafts/reg-1/1').build(); + if (overrides.firstChildParams === null) { + (mockActivatedRoute as unknown as Record)['firstChild'] = null; + (mockActivatedRoute.snapshot as unknown as Record)['firstChild'] = null; + } else { + const childParams = overrides.firstChildParams ?? { id: 'reg-1', step: '1' }; + (mockActivatedRoute.snapshot as unknown as Record)['firstChild'] = { params: childParams }; + (mockActivatedRoute as unknown as Record)['firstChild'] = { snapshot: { params: childParams } }; + } + + const mockRouter = RouterMockBuilder.create() + .withUrl(overrides.routerUrl ?? '/registries/drafts/reg-1/1') + .build(); + if (overrides.routerEvents !== undefined) { + mockRouter.events = overrides.routerEvents as RouterMockType['events']; + } else { mockRouter.events = of(new NavigationEnd(1, '/', '/')); + } - await TestBed.configureTestingModule({ - imports: [DraftsComponent, OSFTestingModule, ...MockComponents(StepperComponent, SubHeaderComponent)], - providers: [ - MockProvider(ActivatedRoute, mockActivatedRoute), - MockProvider(Router, mockRouter), - provideMockStore({ - signals: [ - { selector: RegistriesSelectors.getPagesSchema, value: MOCK_PAGES }, - { selector: RegistriesSelectors.getDraftRegistration, value: MOCK_DRAFT }, - { selector: RegistriesSelectors.getStepsState, value: {} }, - { selector: RegistriesSelectors.getStepsData, value: {} }, - { selector: ContributorsSelectors.getContributors, value: [] }, - { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, - ], - }), - ], - }).compileComponents(); + const defaultSignals: { selector: unknown; value: unknown }[] = [ + { selector: RegistriesSelectors.getPagesSchema, value: MOCK_PAGES_SCHEMA }, + { selector: RegistriesSelectors.getDraftRegistration, value: MOCK_DRAFT_REGISTRATION }, + { selector: RegistriesSelectors.getRegistrationLicense, value: { id: 'mit' } }, + { selector: RegistriesSelectors.getStepsState, value: {} }, + { selector: RegistriesSelectors.getStepsData, value: {} }, + { selector: ContributorsSelectors.getContributors, value: [{ id: 'c1' }] }, + { selector: SubjectsSelectors.getSelectedSubjects, value: [{ id: 's1' }] }, + ]; + + const signals = overrides.selectorOverrides + ? defaultSignals.map((s) => { + const override = overrides.selectorOverrides!.find((o) => o.selector === s.selector); + return override ? { ...s, value: override.value } : s; + }) + : defaultSignals; + + TestBed.configureTestingModule({ + imports: [DraftsComponent, ...MockComponents(StepperComponent, SubHeaderComponent)], + providers: [ + provideOSFCore(), + MockProvider(ActivatedRoute, mockActivatedRoute), + MockProvider(Router, mockRouter), + MockProvider(LoaderService, new LoaderServiceMock()), + provideMockStore({ signals }), + ], + }); + + const store = TestBed.inject(Store); + const fixture = TestBed.createComponent(DraftsComponent); + const component = fixture.componentInstance; + + return { + fixture, + component, + store, + mockRouter: TestBed.inject(Router) as unknown as RouterMockType, + mockActivatedRoute, + }; +} + +describe('DraftsComponent', () => { + let component: DraftsComponent; + let fixture: ComponentFixture; + let store: Store; + let mockRouter: RouterMockType; - fixture = TestBed.createComponent(DraftsComponent); - component = fixture.componentInstance; + beforeEach(() => { + const result = setup(); + fixture = result.fixture; + component = result.component; + store = result.store; + mockRouter = result.mockRouter; }); it('should create', () => { expect(component).toBeTruthy(); }); + it('should resolve registrationId from route firstChild', () => { + expect(component.registrationId).toBe('reg-1'); + }); + it('should compute isReviewPage from router url', () => { expect(component.isReviewPage).toBe(false); - const router = TestBed.inject(Router) as any; - router.url = '/registries/drafts/reg-1/review'; + (mockRouter as unknown as Record)['url'] = '/registries/drafts/reg-1/review'; expect(component.isReviewPage).toBe(true); }); it('should build steps from pages and defaults', () => { const steps = component.steps(); - expect(Array.isArray(steps)).toBe(true); expect(steps.length).toBe(3); + expect(steps[0].routeLink).toBe('metadata'); + expect(steps[1].label).toBe('Page 1'); + expect(steps[2].routeLink).toBe('review'); + }); + + it('should set currentStepIndex from route params', () => { + expect(component.currentStepIndex()).toBe(1); + }); + + it('should compute currentStep from steps and currentStepIndex', () => { expect(component.currentStep()).toBeDefined(); + expect(component.currentStep().label).toBe('Page 1'); + }); + + it('should compute isMetaDataInvalid as false when all fields present', () => { + expect(component.isMetaDataInvalid()).toBe(false); + }); + + it('should navigate and update currentStepIndex on stepChange', () => { + component.stepChange({ index: 0, label: 'Metadata', value: '' }); + + expect(component.currentStepIndex()).toBe(0); + expect(mockRouter.navigate).toHaveBeenCalledWith(['/registries/drafts/reg-1/', 'metadata']); + }); + + it('should dispatch clearState on destroy', () => { + (store.dispatch as jest.Mock).mockClear(); + + component.ngOnDestroy(); + + expect(store.dispatch).toHaveBeenCalledWith(new ClearState()); + }); + + it('should compute isMetaDataInvalid as true when title is missing', () => { + const { component: c } = setup({ + selectorOverrides: [ + { selector: RegistriesSelectors.getDraftRegistration, value: { ...MOCK_DRAFT_REGISTRATION, title: '' } }, + ], + }); + + expect(c.isMetaDataInvalid()).toBe(true); + }); + + it('should compute isMetaDataInvalid as true when subjects are empty', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: SubjectsSelectors.getSelectedSubjects, value: [] }], + }); + + expect(c.isMetaDataInvalid()).toBe(true); + }); + + it('should set metadata step as invalid when license is missing', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getRegistrationLicense, value: null }], + }); + + const steps = c.steps(); + expect(steps[0].invalid).toBe(true); + }); + + it('should dispatch getDraftRegistration when draftRegistration is null', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getDraftRegistration, value: null }], + }); + + expect(c).toBeTruthy(); + }); + + it('should dispatch getContributors when contributors list is empty', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: ContributorsSelectors.getContributors, value: [] }], + }); + + expect(c).toBeTruthy(); + }); + + it('should dispatch getSubjects when selectedSubjects list is empty', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: SubjectsSelectors.getSelectedSubjects, value: [] }], + }); + + expect(c).toBeTruthy(); + }); + + it('should dispatch all actions when all initial data is missing', () => { + const { component: c } = setup({ + selectorOverrides: [ + { selector: RegistriesSelectors.getDraftRegistration, value: null }, + { selector: ContributorsSelectors.getContributors, value: [] }, + { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, + ], + }); + + expect(c).toBeTruthy(); + }); + + it('should hide loader after schema blocks are fetched', fakeAsync(() => { + fixture.detectChanges(); + tick(); + + const loaderService = TestBed.inject(LoaderService); + expect(loaderService.hide).toHaveBeenCalled(); + })); + + it('should not fetch schema blocks when draft has no registrationSchemaId', () => { + const { fixture: f } = setup({ + selectorOverrides: [ + { + selector: RegistriesSelectors.getDraftRegistration, + value: { ...MOCK_DRAFT_REGISTRATION, registrationSchemaId: '' }, + }, + ], + }); + + f.detectChanges(); + + const loaderService = TestBed.inject(LoaderService); + expect(loaderService.hide).not.toHaveBeenCalled(); + }); + + it('should set currentStepIndex to pages.length + 1 on review navigation', () => { + const { component: c } = setup({ + routerUrl: '/registries/drafts/reg-1/review', + firstChildParams: null, + }); + + expect(c.currentStepIndex()).toBe(MOCK_PAGES_SCHEMA.length + 1); + }); + + it('should reset currentStepIndex to 0 when no step and not review', () => { + const { component: c } = setup({ + routerUrl: '/registries/drafts/reg-1/metadata', + firstChildParams: { id: 'reg-1' }, + }); + + expect(c.currentStepIndex()).toBe(0); + }); + + it('should set currentStepIndex from step param on navigation', () => { + const { component: c } = setup({ + firstChildParams: { id: 'reg-1', step: '2' }, + }); + + expect(c.currentStepIndex()).toBe(2); + }); + + it('should sync currentStepIndex to review step when on review page', () => { + const { component: c } = setup({ + routerUrl: '/registries/drafts/reg-1/review', + firstChildParams: null, + }); + + expect(c.currentStepIndex()).toBe(MOCK_PAGES_SCHEMA.length + 1); + }); + + it('should include questions from sections when building steps', () => { + const pagesWithSections = [...MOCK_PAGES_SCHEMA, MOCK_REGISTRIES_PAGE_WITH_SECTIONS]; + + const { component: c } = setup({ + selectorOverrides: [ + { selector: RegistriesSelectors.getPagesSchema, value: pagesWithSections }, + { selector: RegistriesSelectors.getStepsData, value: { field1: 'v1', field3: 'v3' } }, + ], + }); + + const steps = c.steps(); + expect(steps.length).toBe(4); + expect(steps[2].label).toBe('Page 2'); + expect(steps[2].touched).toBe(true); + }); + + it('should not mark section step as touched when no data for section questions', () => { + const pagesWithSections = [...MOCK_PAGES_SCHEMA, MOCK_REGISTRIES_PAGE_WITH_SECTIONS]; + + const { component: c } = setup({ + selectorOverrides: [ + { selector: RegistriesSelectors.getPagesSchema, value: pagesWithSections }, + { selector: RegistriesSelectors.getStepsData, value: {} }, + ], + }); + + const steps = c.steps(); + expect(steps[2].touched).toBe(false); + }); + + it('should mark step as invalid when required field has empty array', () => { + const { component: c } = setup({ + firstChildParams: { id: 'reg-1', step: '2' }, + selectorOverrides: [ + { selector: RegistriesSelectors.getStepsData, value: { field1: [], field2: 'v2' } }, + { selector: RegistriesSelectors.getStepsState, value: { 1: { invalid: true, touched: true } } }, + ], + }); + + const steps = c.steps(); + expect(steps[1].invalid).toBe(true); + }); + + it('should not mark step as invalid when required field has non-empty array', () => { + const { component: c } = setup({ + firstChildParams: { id: 'reg-1', step: '2' }, + selectorOverrides: [{ selector: RegistriesSelectors.getStepsData, value: { field1: ['item'], field2: 'v2' } }], + }); + + const steps = c.steps(); + expect(steps[1].invalid).toBe(false); + }); + + it('should not mark step as invalid when required field has truthy value', () => { + const { component: c } = setup({ + firstChildParams: { id: 'reg-1', step: '2' }, + selectorOverrides: [{ selector: RegistriesSelectors.getStepsData, value: { field1: 'value', field2: '' } }], + }); + + const steps = c.steps(); + expect(steps[1].invalid).toBe(false); + }); + + it('should mark step as invalid when required field is falsy', () => { + const { component: c } = setup({ + firstChildParams: { id: 'reg-1', step: '2' }, + selectorOverrides: [ + { selector: RegistriesSelectors.getStepsData, value: { field1: '', field2: 'v2' } }, + { selector: RegistriesSelectors.getStepsState, value: { 1: { invalid: true, touched: true } } }, + ], + }); + + const steps = c.steps(); + expect(steps[1].invalid).toBe(true); + }); + + it('should detect hasStepData with array data', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getStepsData, value: { field1: ['item1'] } }], + }); + + const steps = c.steps(); + expect(steps[1].touched).toBe(true); + }); + + it('should not detect hasStepData with empty array', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getStepsData, value: { field1: [] } }], + }); + + const steps = c.steps(); + expect(steps[1].touched).toBe(false); + }); + + it('should validate previous steps when currentStepIndex > 0', () => { + const { component: c } = setup({ + firstChildParams: { id: 'reg-1', step: '1' }, + selectorOverrides: [{ selector: RegistriesSelectors.getStepsData, value: { field1: 'v1' } }], + }); + + expect(c.currentStepIndex()).toBe(1); + expect(c).toBeTruthy(); + }); + + it('should not validate steps when currentStepIndex is 0', () => { + const { component: c } = setup({ + firstChildParams: { id: 'reg-1', step: '0' }, + routerUrl: '/registries/drafts/reg-1/metadata', + }); + + expect(c.currentStepIndex()).toBe(0); + }); + + it('should validate metadata step as invalid when license is missing', () => { + const { component: c } = setup({ + firstChildParams: { id: 'reg-1', step: '1' }, + selectorOverrides: [ + { selector: RegistriesSelectors.getRegistrationLicense, value: null }, + { selector: RegistriesSelectors.getStepsData, value: { field1: 'v1' } }, + ], + }); + + expect(c.isMetaDataInvalid()).toBe(true); + }); + + it('should validate metadata step as invalid when description is missing', () => { + const { component: c } = setup({ + firstChildParams: { id: 'reg-1', step: '1' }, + selectorOverrides: [ + { selector: RegistriesSelectors.getDraftRegistration, value: { ...MOCK_DRAFT_REGISTRATION, description: '' } }, + { selector: RegistriesSelectors.getStepsData, value: { field1: 'v1' } }, + ], + }); + + expect(c.isMetaDataInvalid()).toBe(true); + }); + + it('should default registrationId to empty string when no firstChild', () => { + const { component: c } = setup({ + routerUrl: '/registries/drafts/', + firstChildParams: null, + }); + + expect(c.registrationId).toBe(''); + }); + + it('should default currentStepIndex to 0 when step param is absent', () => { + const { component: c } = setup({ + firstChildParams: { id: 'reg-1' }, + routerUrl: '/registries/drafts/reg-1/metadata', + }); + + expect(c.currentStepIndex()).toBe(0); + }); + + it('should mark step as touched when stepsData has matching keys', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getStepsData, value: MOCK_STEPS_DATA }], + }); + + const steps = c.steps(); + expect(steps[1].touched).toBe(true); }); }); diff --git a/src/app/features/registries/components/drafts/drafts.component.ts b/src/app/features/registries/components/drafts/drafts.component.ts index a1d9fd448..f1579427a 100644 --- a/src/app/features/registries/components/drafts/drafts.component.ts +++ b/src/app/features/registries/components/drafts/drafts.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, switchMap, take } from 'rxjs'; import { ChangeDetectionStrategy, @@ -12,11 +12,10 @@ import { effect, inject, OnDestroy, - Signal, signal, untracked, } from '@angular/core'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; import { ActivatedRoute, NavigationEnd, Router, RouterOutlet } from '@angular/router'; import { StepperComponent } from '@osf/shared/components/stepper/stepper.component'; @@ -37,7 +36,6 @@ import { ClearState, FetchDraft, FetchSchemaBlocks, RegistriesSelectors, UpdateS templateUrl: './drafts.component.html', styleUrl: './drafts.component.scss', changeDetection: ChangeDetectionStrategy.OnPush, - providers: [TranslateService], }) export class DraftsComponent implements OnDestroy { private readonly router = inject(Router); @@ -48,13 +46,12 @@ export class DraftsComponent implements OnDestroy { readonly pages = select(RegistriesSelectors.getPagesSchema); readonly draftRegistration = select(RegistriesSelectors.getDraftRegistration); - stepsState = select(RegistriesSelectors.getStepsState); - readonly stepsData = select(RegistriesSelectors.getStepsData); - selectedSubjects = select(SubjectsSelectors.getSelectedSubjects); - initialContributors = select(ContributorsSelectors.getContributors); - readonly contributors = select(ContributorsSelectors.getContributors); - readonly subjects = select(SubjectsSelectors.getSelectedSubjects); - readonly registrationLicense = select(RegistriesSelectors.getRegistrationLicense); + readonly stepsState = select(RegistriesSelectors.getStepsState); + + private readonly stepsData = select(RegistriesSelectors.getStepsData); + private readonly registrationLicense = select(RegistriesSelectors.getRegistrationLicense); + private readonly selectedSubjects = select(SubjectsSelectors.getSelectedSubjects); + private readonly contributors = select(ContributorsSelectors.getContributors); private readonly actions = createDispatchMap({ getSchemaBlocks: FetchSchemaBlocks, @@ -69,146 +66,161 @@ export class DraftsComponent implements OnDestroy { return this.router.url.includes('/review'); } - isMetaDataInvalid = computed(() => { - return ( + isMetaDataInvalid = computed( + () => !this.draftRegistration()?.title || !this.draftRegistration()?.description || !this.registrationLicense() || !this.selectedSubjects()?.length - ); - }); - - defaultSteps: StepOption[] = []; - - isLoaded = false; + ); - steps: Signal = computed(() => { + steps = computed(() => { const stepState = this.stepsState(); const stepData = this.stepsData(); - this.defaultSteps = DEFAULT_STEPS.map((step) => ({ - ...step, - label: this.translateService.instant(step.label), - invalid: stepState?.[step.index]?.invalid || false, + + const metadataStep: StepOption = { + ...DEFAULT_STEPS[0], + label: this.translateService.instant(DEFAULT_STEPS[0].label), + invalid: this.isMetaDataInvalid(), + touched: true, + }; + + const customSteps: StepOption[] = this.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 || this.hasStepData(page, stepData), })); - this.defaultSteps[0].invalid = this.isMetaDataInvalid(); - this.defaultSteps[0].touched = true; - const customSteps = this.pages().map((page, index) => { - const pageStep = this.pages()[index]; - const allQuestions = this.getAllQuestions(pageStep); - const wasTouched = - allQuestions?.some((question) => { - const questionData = stepData[question.responseKey!]; - return Array.isArray(questionData) ? questionData.length : questionData; - }) || false; - return { - index: index + 1, - label: page.title, - value: page.id, - routeLink: `${index + 1}`, - invalid: stepState?.[index + 1]?.invalid || false, - touched: stepState?.[index + 1]?.touched || wasTouched, - }; - }); - return [ - this.defaultSteps[0], - ...customSteps, - { ...this.defaultSteps[1], index: customSteps.length + 1, invalid: false }, - ]; + const reviewStep: StepOption = { + ...DEFAULT_STEPS[1], + label: this.translateService.instant(DEFAULT_STEPS[1].label), + index: customSteps.length + 1, + invalid: false, + }; + + return [metadataStep, ...customSteps, reviewStep]; }); + registrationId = this.route.snapshot.firstChild?.params['id'] || ''; + currentStepIndex = signal( this.route.snapshot.firstChild?.params['step'] ? +this.route.snapshot.firstChild?.params['step'] : 0 ); currentStep = computed(() => this.steps()[this.currentStepIndex()]); - registrationId = this.route.snapshot.firstChild?.params['id'] || ''; - constructor() { + this.loadInitialData(); + this.setupSchemaLoader(); + this.setupRouteWatcher(); + this.setupReviewStepSync(); + this.setupStepValidation(); + } + + ngOnDestroy(): void { + this.actions.clearState(); + } + + stepChange(step: StepOption): void { + this.currentStepIndex.set(step.index); + this.router.navigate([`/registries/drafts/${this.registrationId}/`, this.steps()[step.index].routeLink]); + } + + private loadInitialData() { + this.loaderService.show(); + + if (!this.draftRegistration()) { + this.actions.getDraftRegistration(this.registrationId); + } + + if (!this.contributors()?.length) { + this.actions.getContributors(this.registrationId, ResourceType.DraftRegistration); + } + + if (!this.selectedSubjects()?.length) { + this.actions.getSubjects(this.registrationId, ResourceType.DraftRegistration); + } + } + + private setupSchemaLoader() { + toObservable(this.draftRegistration) + .pipe( + filter((draft) => !!draft?.registrationSchemaId), + take(1), + switchMap((draft) => this.actions.getSchemaBlocks(draft!.registrationSchemaId)), + takeUntilDestroyed(this.destroyRef) + ) + .subscribe(() => this.loaderService.hide()); + } + + private setupRouteWatcher() { this.router.events .pipe( - takeUntilDestroyed(this.destroyRef), - filter((event): event is NavigationEnd => event instanceof NavigationEnd) + filter((event): event is NavigationEnd => event instanceof NavigationEnd), + takeUntilDestroyed(this.destroyRef) ) .subscribe(() => { const step = this.route.firstChild?.snapshot.params['step']; 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); } }); + } - this.loaderService.show(); - if (!this.draftRegistration()) { - this.actions.getDraftRegistration(this.registrationId); - } - if (!this.contributors()?.length) { - this.actions.getContributors(this.registrationId, ResourceType.DraftRegistration); - } - if (!this.subjects()?.length) { - this.actions.getSubjects(this.registrationId, ResourceType.DraftRegistration); - } - effect(() => { - const registrationSchemaId = this.draftRegistration()?.registrationSchemaId; - if (registrationSchemaId && !this.isLoaded) { - this.actions - .getSchemaBlocks(registrationSchemaId || '') - .pipe( - tap(() => { - this.isLoaded = true; - this.loaderService.hide(); - }) - ) - .subscribe(); - } - }); - + private setupReviewStepSync() { effect(() => { const reviewStepIndex = this.pages().length + 1; if (this.isReviewPage) { this.currentStepIndex.set(reviewStepIndex); } }); + } + private setupStepValidation() { effect(() => { const stepState = untracked(() => this.stepsState()); - if (this.currentStepIndex() > 0) { + const currentIndex = this.currentStepIndex(); + + if (currentIndex > 0) { this.actions.updateStepState('0', this.isMetaDataInvalid(), stepState?.[0]?.touched || false); } - if (this.pages().length && this.currentStepIndex() > 0 && this.stepsData()) { - for (let i = 1; i < this.currentStepIndex(); i++) { - const pageStep = this.pages()[i - 1]; - const allQuestions = this.getAllQuestions(pageStep); - const isStepInvalid = - allQuestions?.some((question) => { - const questionData = this.stepsData()[question.responseKey!]; - return question.required && (Array.isArray(questionData) ? !questionData.length : !questionData); - }) || false; - this.actions.updateStepState(i.toString(), isStepInvalid, stepState?.[i]?.touched || false); + + if (this.pages().length && currentIndex > 0 && this.stepsData()) { + for (let i = 1; i < currentIndex; i++) { + const page = this.pages()[i - 1]; + const invalid = this.isPageInvalid(page, this.stepsData()); + this.actions.updateStepState(i.toString(), invalid, stepState?.[i]?.touched || false); } } }); } - stepChange(step: StepOption): void { - this.currentStepIndex.set(step.index); - const pageLink = this.steps()[step.index].routeLink; - this.router.navigate([`/registries/drafts/${this.registrationId}/`, pageLink]); + private getAllQuestions(page: PageSchema): Question[] { + return [...(page?.questions ?? []), ...(page?.sections?.flatMap((section) => section.questions ?? []) ?? [])]; } - private getAllQuestions(pageStep: PageSchema): Question[] { - return [ - ...(pageStep?.questions ?? []), - ...(pageStep?.sections?.flatMap((section) => section.questions ?? []) ?? []), - ]; + private hasStepData(page: PageSchema, stepData: Record): boolean { + return ( + this.getAllQuestions(page).some((question) => { + const data = stepData[question.responseKey!]; + return Array.isArray(data) ? data.length : data; + }) || false + ); } - ngOnDestroy(): void { - this.actions.clearState(); + private isPageInvalid(page: PageSchema, stepData: Record): boolean { + return ( + this.getAllQuestions(page).some((question) => { + const data = stepData[question.responseKey!]; + return question.required && (Array.isArray(data) ? !data.length : !data); + }) || false + ); } } diff --git a/src/app/features/registries/components/files-control/files-control.component.html b/src/app/features/registries/components/files-control/files-control.component.html index bf53c0a2f..8d3350ae2 100644 --- a/src/app/features/registries/components/files-control/files-control.component.html +++ b/src/app/features/registries/components/files-control/files-control.component.html @@ -13,7 +13,7 @@ severity="success" [icon]="'fas fa-plus'" [label]="'files.actions.createFolder' | translate" - (click)="createFolder()" + (onClick)="createFolder()" > @@ -24,7 +24,7 @@ severity="success" [icon]="'fas fa-upload'" [label]="'files.actions.uploadFile' | translate" - (click)="fileInput.click()" + (onClick)="fileInput.click()" > @@ -50,6 +50,8 @@ [viewOnly]="filesViewOnly()" [resourceId]="projectId()" [provider]="provider()" + [selectedFiles]="filesSelection" + (selectFile)="onFileTreeSelected($event)" (entryFileClicked)="selectFile($event)" (uploadFilesConfirmed)="uploadFiles($event)" (loadFiles)="onLoadFiles($event)" diff --git a/src/app/features/registries/components/files-control/files-control.component.spec.ts b/src/app/features/registries/components/files-control/files-control.component.spec.ts index 79257199d..e1a26b51e 100644 --- a/src/app/features/registries/components/files-control/files-control.component.spec.ts +++ b/src/app/features/registries/components/files-control/files-control.component.spec.ts @@ -1,13 +1,26 @@ +import { Store } from '@ngxs/store'; + import { MockComponents, MockProvider } from 'ng-mocks'; import { of, Subject } from 'rxjs'; +import { HttpEventType } from '@angular/common/http'; +import { signal, WritableSignal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { HelpScoutService } from '@core/services/help-scout.service'; -import { RegistriesSelectors } from '@osf/features/registries/store'; +import { + CreateFolder, + GetFiles, + RegistriesSelectors, + SetFilesIsLoading, + SetRegistriesCurrentFolder, +} from '@osf/features/registries/store'; import { FileUploadDialogComponent } from '@osf/shared/components/file-upload-dialog/file-upload-dialog.component'; +import { FilesTreeComponent } from '@osf/shared/components/files-tree/files-tree.component'; import { LoadingSpinnerComponent } from '@osf/shared/components/loading-spinner/loading-spinner.component'; +import { FILE_SIZE_LIMIT } from '@osf/shared/constants/files-limits.const'; +import { FileModel } from '@osf/shared/models/files/file.model'; +import { FileFolderModel } from '@osf/shared/models/files/file-folder.model'; import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { CustomDialogService } from '@osf/shared/services/custom-dialog.service'; import { FilesService } from '@osf/shared/services/files.service'; @@ -15,57 +28,73 @@ import { ToastService } from '@osf/shared/services/toast.service'; import { FilesControlComponent } from './files-control.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 { HelpScoutServiceMockFactory } from '@testing/providers/help-scout.service.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; +import { MockComponentWithSignal } from '@testing/providers/component-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 { ToastServiceMock, ToastServiceMockType } from '@testing/providers/toast-provider.mock'; -describe('Component: File Control', () => { +describe('FilesControlComponent', () => { let component: FilesControlComponent; let fixture: ComponentFixture; - let helpScoutService: HelpScoutService; - let mockFilesService: jest.Mocked; - let mockDialogService: ReturnType; - let mockToastService: ReturnType; - let mockCustomConfirmationService: ReturnType; - const currentFolder = { - links: { newFolder: '/new-folder', upload: '/upload' }, - relationships: { filesLink: '/files-link' }, - } as any; - - beforeEach(async () => { - mockFilesService = { uploadFile: jest.fn(), getFileGuid: jest.fn() } as any; + let store: Store; + let mockFilesService: { uploadFile: jest.Mock; getFileGuid: jest.Mock }; + let mockDialogService: CustomDialogServiceMockType; + let currentFolderSignal: WritableSignal; + let toastService: ToastServiceMockType; + + const CURRENT_FOLDER = { + links: { newFolder: '/new-folder', upload: '/upload', filesLink: '/files-link' }, + } as FileFolderModel; + + beforeEach(() => { + mockFilesService = { uploadFile: jest.fn(), getFileGuid: jest.fn() }; mockDialogService = CustomDialogServiceMockBuilder.create().withDefaultOpen().build(); - mockToastService = ToastServiceMockBuilder.create().build(); - mockCustomConfirmationService = CustomConfirmationServiceMockBuilder.create().build(); - helpScoutService = HelpScoutServiceMockFactory(); - - await TestBed.configureTestingModule({ - imports: [ - FilesControlComponent, - OSFTestingModule, - ...MockComponents(LoadingSpinnerComponent, FileUploadDialogComponent), - ], + currentFolderSignal = signal(CURRENT_FOLDER); + toastService = ToastServiceMock.simple(); + + TestBed.configureTestingModule({ + imports: [FilesControlComponent, ...MockComponents(LoadingSpinnerComponent, FileUploadDialogComponent)], providers: [ + provideOSFCore(), + MockProvider(ToastService, toastService), + MockProvider(CustomConfirmationService), MockProvider(FilesService, mockFilesService), MockProvider(CustomDialogService, mockDialogService), - MockProvider(ToastService, mockToastService), - MockProvider(CustomConfirmationService, mockCustomConfirmationService), - { provide: HelpScoutService, useValue: helpScoutService }, provideMockStore({ signals: [ { selector: RegistriesSelectors.getFiles, value: [] }, { selector: RegistriesSelectors.getFilesTotalCount, value: 0 }, { selector: RegistriesSelectors.isFilesLoading, value: false }, - { selector: RegistriesSelectors.getCurrentFolder, value: currentFolder }, + { selector: RegistriesSelectors.getCurrentFolder, value: currentFolderSignal }, ], }), ], - }).compileComponents(); + }).overrideComponent(FilesControlComponent, { + remove: { imports: [FilesTreeComponent] }, + add: { + imports: [ + MockComponentWithSignal('osf-files-tree', [ + 'files', + 'selectionMode', + 'totalCount', + 'storage', + 'currentFolder', + 'isLoading', + 'scrollHeight', + 'viewOnly', + 'resourceId', + 'provider', + 'selectedFiles', + ]), + ], + }, + }); - helpScoutService = TestBed.inject(HelpScoutService); + store = TestBed.inject(Store); fixture = TestBed.createComponent(FilesControlComponent); component = fixture.componentInstance; fixture.componentRef.setInput('attachedFiles', []); @@ -76,47 +105,148 @@ describe('Component: File Control', () => { fixture.detectChanges(); }); - it('should have a default value', () => { - expect(component.fileIsUploading()).toBeFalsy(); + it('should create with default signal values', () => { + expect(component).toBeTruthy(); + expect(component.fileIsUploading()).toBe(false); + expect(component.progress()).toBe(0); + expect(component.fileName()).toBe(''); }); - it('should called the helpScoutService', () => { - expect(helpScoutService.setResourceType).toHaveBeenCalledWith('files'); + it('should do nothing when no file is selected', () => { + const event = { target: { files: [] } } as unknown as Event; + const uploadSpy = jest.spyOn(component, 'uploadFiles'); + + component.onFileSelected(event); + + expect(uploadSpy).not.toHaveBeenCalled(); + }); + + it('should show warning when file exceeds size limit', () => { + const oversizedFile = new File([''], 'big.bin'); + Object.defineProperty(oversizedFile, 'size', { value: FILE_SIZE_LIMIT }); + const event = { target: { files: [oversizedFile] } } as unknown as Event; + + component.onFileSelected(event); + + expect(toastService.showWarn).toHaveBeenCalledWith('shared.files.limitText'); + }); + + it('should upload valid file', () => { + const file = new File(['data'], 'test.txt'); + const event = { target: { files: [file] } } as unknown as Event; + const uploadSpy = jest.spyOn(component, 'uploadFiles').mockImplementation(); + + component.onFileSelected(event); + + expect(uploadSpy).toHaveBeenCalledWith(file); }); - it('should open create folder dialog and trigger files update', () => { + it('should open dialog and dispatch createFolder on confirm', () => { const onClose$ = new Subject(); - (mockDialogService.open as any).mockReturnValue({ onClose: onClose$ }); - const updateSpy = jest.spyOn(component, 'updateFilesList').mockReturnValue(of(void 0)); + mockDialogService.open.mockReturnValue({ onClose: onClose$ } as any); + (store.dispatch as jest.Mock).mockClear(); component.createFolder(); expect(mockDialogService.open).toHaveBeenCalled(); onClose$.next('New Folder'); - expect(updateSpy).toHaveBeenCalled(); + expect(store.dispatch).toHaveBeenCalledWith(new CreateFolder('/new-folder', 'New Folder')); }); - it('should upload files, update progress and select uploaded file', () => { - const file = new File(['data'], 'test.txt', { type: 'text/plain' }); - const progress = { type: 1, loaded: 50, total: 100 } as any; - const response = { type: 4, body: { data: { id: 'files/abc' } } } as any; + it('should upload file, track progress, and select uploaded file', () => { + const file = new File(['data'], 'test.txt'); + const progress = { type: HttpEventType.UploadProgress, loaded: 50, total: 100 }; + const response = { type: HttpEventType.Response, body: { data: { id: 'files/abc' } } }; - (mockFilesService.uploadFile as any).mockReturnValue(of(progress, response)); - (mockFilesService.getFileGuid as any).mockReturnValue(of({ id: 'abc' })); + mockFilesService.uploadFile.mockReturnValue(of(progress, response)); + mockFilesService.getFileGuid.mockReturnValue(of({ id: 'abc' } as FileModel)); const selectSpy = jest.spyOn(component, 'selectFile'); component.uploadFiles(file); + expect(mockFilesService.uploadFile).toHaveBeenCalledWith(file, '/upload'); - expect(selectSpy).toHaveBeenCalledWith({ id: 'abc' } as any); + expect(component.progress()).toBe(50); + expect(selectSpy).toHaveBeenCalledWith({ id: 'abc' } as FileModel); + }); + + it('should not upload when no upload link', () => { + currentFolderSignal.set({ links: {} } as FileFolderModel); + + const file = new File(['data'], 'test.txt'); + component.uploadFiles(file); + + expect(mockFilesService.uploadFile).not.toHaveBeenCalled(); }); - it('should emit attachFile when selectFile and not view-only', (done) => { - const file = { id: 'file-1' } as any; + it('should handle File array input', () => { + const file = new File(['data'], 'test.txt'); + mockFilesService.uploadFile.mockReturnValue(of({ type: HttpEventType.Sent })); + + component.uploadFiles([file]); + + expect(mockFilesService.uploadFile).toHaveBeenCalledWith(file, '/upload'); + }); + + it('should emit attachFile when not view-only', (done) => { + const file = { id: 'file-1' } as FileModel; component.attachFile.subscribe((f) => { expect(f).toEqual(file); done(); }); component.selectFile(file); }); + + it('should not emit attachFile when filesViewOnly is true', () => { + fixture.componentRef.setInput('filesViewOnly', true); + fixture.detectChanges(); + + const emitSpy = jest.spyOn(component.attachFile, 'emit'); + component.selectFile({ id: 'file-1' } as FileModel); + + expect(emitSpy).not.toHaveBeenCalled(); + }); + + it('should dispatch getFiles on onLoadFiles', () => { + (store.dispatch as jest.Mock).mockClear(); + + component.onLoadFiles({ link: '/files', page: 2 }); + + expect(store.dispatch).toHaveBeenCalledWith(new GetFiles('/files', 2)); + }); + + it('should dispatch setCurrentFolder', () => { + const folder = { id: 'folder-1' } as FileFolderModel; + (store.dispatch as jest.Mock).mockClear(); + + component.setCurrentFolder(folder); + + expect(store.dispatch).toHaveBeenCalledWith(new SetRegistriesCurrentFolder(folder)); + }); + + it('should add file to filesSelection and deduplicate', () => { + const file = { id: 'file-1' } as FileModel; + + component.onFileTreeSelected(file); + component.onFileTreeSelected(file); + + expect(component.filesSelection).toEqual([file]); + }); + + it('should not open dialog when no newFolder link', () => { + currentFolderSignal.set({ links: {} } as FileFolderModel); + + component.createFolder(); + + expect(mockDialogService.open).not.toHaveBeenCalled(); + }); + + it('should not dispatch getFiles when currentFolder has no filesLink', () => { + (store.dispatch as jest.Mock).mockClear(); + currentFolderSignal.set({ links: {} } as FileFolderModel); + fixture.detectChanges(); + + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(SetFilesIsLoading)); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(GetFiles)); + }); }); diff --git a/src/app/features/registries/components/files-control/files-control.component.ts b/src/app/features/registries/components/files-control/files-control.component.ts index ba1b578d8..423a65d45 100644 --- a/src/app/features/registries/components/files-control/files-control.component.ts +++ b/src/app/features/registries/components/files-control/files-control.component.ts @@ -5,24 +5,12 @@ import { TranslatePipe } from '@ngx-translate/core'; import { TreeDragDropService } from 'primeng/api'; import { Button } from 'primeng/button'; -import { EMPTY, filter, finalize, Observable, shareReplay, take } from 'rxjs'; +import { filter, finalize, switchMap, take } from 'rxjs'; import { HttpEventType } from '@angular/common/http'; -import { - ChangeDetectionStrategy, - Component, - DestroyRef, - effect, - inject, - input, - OnDestroy, - output, - signal, -} from '@angular/core'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { FormsModule, ReactiveFormsModule } from '@angular/forms'; - -import { HelpScoutService } from '@core/services/help-scout.service'; +import { ChangeDetectionStrategy, Component, DestroyRef, inject, input, output, signal } from '@angular/core'; +import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; + import { CreateFolderDialogComponent } from '@osf/features/files/components'; import { FileUploadDialogComponent } from '@osf/shared/components/file-upload-dialog/file-upload-dialog.component'; import { FilesTreeComponent } from '@osf/shared/components/files-tree/files-tree.component'; @@ -47,12 +35,10 @@ import { @Component({ selector: 'osf-files-control', imports: [ - FilesTreeComponent, Button, + FilesTreeComponent, LoadingSpinnerComponent, FileUploadDialogComponent, - FormsModule, - ReactiveFormsModule, TranslatePipe, ClearFileDirective, ], @@ -61,19 +47,18 @@ import { changeDetection: ChangeDetectionStrategy.OnPush, providers: [TreeDragDropService], }) -export class FilesControlComponent implements OnDestroy { +export class FilesControlComponent { attachedFiles = input.required[]>(); - attachFile = output(); filesLink = input.required(); projectId = input.required(); provider = input.required(); filesViewOnly = input(false); + attachFile = output(); private readonly filesService = inject(FilesService); private readonly customDialogService = inject(CustomDialogService); private readonly destroyRef = inject(DestroyRef); private readonly toastService = inject(ToastService); - private readonly helpScoutService = inject(HelpScoutService); readonly files = select(RegistriesSelectors.getFiles); readonly filesTotalCount = select(RegistriesSelectors.getFilesTotalCount); @@ -85,6 +70,7 @@ export class FilesControlComponent implements OnDestroy { readonly dataLoaded = signal(false); fileIsUploading = signal(false); + filesSelection: FileModel[] = []; private readonly actions = createDispatchMap({ createFolder: CreateFolder, @@ -95,44 +81,26 @@ export class FilesControlComponent implements OnDestroy { }); constructor() { - this.helpScoutService.setResourceType('files'); - effect(() => { - const filesLink = this.filesLink(); - if (filesLink) { - this.actions - .getRootFolders(filesLink) - .pipe(shareReplay(), takeUntilDestroyed(this.destroyRef)) - .subscribe(() => { - this.dataLoaded.set(true); - }); - } - }); - - effect(() => { - const currentFolder = this.currentFolder(); - if (currentFolder) { - this.updateFilesList().subscribe(); - } - }); + this.setupRootFoldersLoader(); + this.setupCurrentFolderWatcher(); } onFileSelected(event: Event): void { const input = event.target as HTMLInputElement; const file = input.files?.[0]; - if (file && file.size >= FILE_SIZE_LIMIT) { + if (!file) return; + + if (file.size >= FILE_SIZE_LIMIT) { this.toastService.showWarn('shared.files.limitText'); return; } - if (!file) return; this.uploadFiles(file); } createFolder(): void { - const currentFolder = this.currentFolder(); - const newFolderLink = currentFolder?.links.newFolder; - + const newFolderLink = this.currentFolder()?.links.newFolder; if (!newFolderLink) return; this.customDialogService @@ -140,35 +108,18 @@ export class FilesControlComponent implements OnDestroy { header: 'files.dialogs.createFolder.title', width: '448px', }) - .onClose.pipe(filter((folderName: string) => !!folderName)) - .subscribe((folderName) => { - this.actions - .createFolder(newFolderLink, folderName) - .pipe( - take(1), - finalize(() => { - this.updateFilesList().subscribe(() => this.fileIsUploading.set(false)); - }) - ) - .subscribe(); - }); - } - - updateFilesList(): Observable { - const currentFolder = this.currentFolder(); - if (currentFolder?.links.filesLink) { - this.actions.setFilesIsLoading(true); - return this.actions.getFiles(currentFolder?.links.filesLink, 1).pipe(take(1)); - } - - return EMPTY; + .onClose.pipe( + filter((folderName: string) => !!folderName), + switchMap((folderName) => this.actions.createFolder(newFolderLink, folderName)), + finalize(() => this.fileIsUploading.set(false)), + takeUntilDestroyed(this.destroyRef) + ) + .subscribe(() => this.refreshFilesList()); } uploadFiles(files: File | File[]): void { - const fileArray = Array.isArray(files) ? files : [files]; - const file = fileArray[0]; - const currentFolder = this.currentFolder(); - const uploadLink = currentFolder?.links.upload; + const file = Array.isArray(files) ? files[0] : files; + const uploadLink = this.currentFolder()?.links.upload; if (!uploadLink) return; this.fileName.set(file.name); @@ -181,7 +132,7 @@ export class FilesControlComponent implements OnDestroy { finalize(() => { this.fileIsUploading.set(false); this.fileName.set(''); - this.updateFilesList(); + this.refreshFilesList(); }) ) .subscribe((event) => { @@ -189,17 +140,14 @@ export class FilesControlComponent implements OnDestroy { this.progress.set(Math.round((event.loaded / event.total) * 100)); } - if (event.type === HttpEventType.Response) { - if (event.body) { - const fileId = event?.body?.data?.id?.split('/').pop(); - if (fileId) { - this.filesService - .getFileGuid(fileId) - .pipe(takeUntilDestroyed(this.destroyRef)) - .subscribe((file) => { - this.selectFile(file); - }); - } + if (event.type === HttpEventType.Response && event.body) { + const fileId = event.body.data?.id?.split('/').pop(); + + if (fileId) { + this.filesService + .getFileGuid(fileId) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((uploadedFile) => this.selectFile(uploadedFile)); } } }); @@ -210,6 +158,11 @@ export class FilesControlComponent implements OnDestroy { this.attachFile.emit(file); } + onFileTreeSelected(file: FileModel): void { + this.filesSelection.push(file); + this.filesSelection = [...new Set(this.filesSelection)]; + } + onLoadFiles(event: { link: string; page: number }) { this.actions.getFiles(event.link, event.page); } @@ -218,7 +171,31 @@ export class FilesControlComponent implements OnDestroy { this.actions.setCurrentFolder(folder); } - ngOnDestroy(): void { - this.helpScoutService.unsetResourceType(); + private setupRootFoldersLoader() { + toObservable(this.filesLink) + .pipe( + filter((link) => !!link), + take(1), + switchMap((link) => this.actions.getRootFolders(link)), + takeUntilDestroyed(this.destroyRef) + ) + .subscribe(() => this.dataLoaded.set(true)); + } + + private setupCurrentFolderWatcher() { + toObservable(this.currentFolder) + .pipe( + filter((folder) => !!folder), + takeUntilDestroyed(this.destroyRef) + ) + .subscribe(() => this.refreshFilesList()); + } + + private refreshFilesList(): void { + const filesLink = this.currentFolder()?.links.filesLink; + if (!filesLink) return; + + this.actions.setFilesIsLoading(true); + this.actions.getFiles(filesLink, 1); } } diff --git a/src/app/features/registries/components/justification-review/justification-review.component.html b/src/app/features/registries/components/justification-review/justification-review.component.html index a282a0fcc..8cf6e62e8 100644 --- a/src/app/features/registries/components/justification-review/justification-review.component.html +++ b/src/app/features/registries/components/justification-review/justification-review.component.html @@ -60,7 +60,7 @@

{{ section.title }}

}
- @if (inProgress) { + @if (inProgress()) { {{ section.title }} (onClick)="submit()" [loading]="isSchemaResponseLoading()" > - } @else if (isUnapproved) { + } @else if (isUnapproved()) { { let component: JustificationReviewComponent; let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; - let mockRouter: ReturnType; - let mockCustomDialogService: ReturnType; - let mockCustomConfirmationService: ReturnType; - let mockToastService: ReturnType; - - const MOCK_SCHEMA_RESPONSE = { - id: 'rev-1', + let store: Store; + let mockRouter: RouterMockType; + let mockCustomDialogService: CustomDialogServiceMockType; + let customConfirmationService: CustomConfirmationServiceMockType; + let toastService: ToastServiceMockType; + + const MOCK_SCHEMA_RESPONSE: Partial = { registrationId: 'reg-1', - reviewsState: RevisionReviewStates.RevisionInProgress, updatedResponseKeys: ['field1'], - } as any; + }; - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'rev-1' }).build(); + beforeEach(() => { + const mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'rev-1' }).build(); mockRouter = RouterMockBuilder.create().withUrl('/x').build(); mockCustomDialogService = CustomDialogServiceMockBuilder.create().withDefaultOpen().build(); - mockCustomConfirmationService = CustomConfirmationServiceMockBuilder.create().build(); - mockToastService = ToastServiceMockBuilder.create().build(); + toastService = ToastServiceMock.simple(); + customConfirmationService = CustomConfirmationServiceMock.simple(); - await TestBed.configureTestingModule({ - imports: [JustificationReviewComponent, OSFTestingModule, MockComponent(RegistrationBlocksDataComponent)], + TestBed.configureTestingModule({ + imports: [JustificationReviewComponent, MockComponent(RegistrationBlocksDataComponent)], providers: [ + provideOSFCore(), MockProvider(ActivatedRoute, mockActivatedRoute), MockProvider(Router, mockRouter), + MockProvider(ToastService, toastService), + MockProvider(CustomConfirmationService, customConfirmationService), MockProvider(CustomDialogService, mockCustomDialogService), - MockProvider(CustomConfirmationService, mockCustomConfirmationService), - MockProvider(ToastService, mockToastService), provideMockStore({ signals: [ { selector: RegistriesSelectors.getPagesSchema, value: MOCK_PAGES_SCHEMA }, @@ -65,8 +77,9 @@ describe('JustificationReviewComponent', () => { ], }), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(JustificationReviewComponent); component = fixture.componentInstance; fixture.detectChanges(); @@ -85,55 +98,46 @@ describe('JustificationReviewComponent', () => { expect(mockRouter.navigate).toHaveBeenCalled(); }); - it('should submit revision for review', () => { - const mockActions = { - handleSchemaResponse: jest.fn().mockReturnValue(of({})), - } as any; - Object.defineProperty(component, 'actions', { value: mockActions }); + it('should dispatch handleSchemaResponse on submit', () => { + (store.dispatch as jest.Mock).mockClear(); component.submit(); - expect(mockActions.handleSchemaResponse).toHaveBeenCalledWith('rev-1', SchemaActionTrigger.Submit); - expect(mockToastService.showSuccess).toHaveBeenCalledWith('registries.justification.successSubmit'); + expect(store.dispatch).toHaveBeenCalledWith(new HandleSchemaResponse('rev-1', SchemaActionTrigger.Submit)); + expect(toastService.showSuccess).toHaveBeenCalledWith('registries.justification.successSubmit'); }); - it('should accept changes', () => { - const mockActions = { - handleSchemaResponse: jest.fn().mockReturnValue(of({})), - } as any; - Object.defineProperty(component, 'actions', { value: mockActions }); + it('should dispatch handleSchemaResponse on acceptChanges', () => { + (store.dispatch as jest.Mock).mockClear(); component.acceptChanges(); - expect(mockActions.handleSchemaResponse).toHaveBeenCalledWith('rev-1', SchemaActionTrigger.Approve); - expect(mockToastService.showSuccess).toHaveBeenCalledWith('registries.justification.successAccept'); + expect(store.dispatch).toHaveBeenCalledWith(new HandleSchemaResponse('rev-1', SchemaActionTrigger.Approve)); + expect(toastService.showSuccess).toHaveBeenCalledWith('registries.justification.successAccept'); expect(mockRouter.navigateByUrl).toHaveBeenCalledWith('/reg-1/overview'); }); - it('should continue editing and show decision recorded toast when confirmed', () => { - jest.spyOn(mockCustomDialogService, 'open').mockReturnValue({ onClose: of(true) } as any); + it('should show decision recorded toast when continueEditing confirmed', () => { + mockCustomDialogService.open.mockReturnValue({ onClose: of(true) } as any); component.continueEditing(); expect(mockCustomDialogService.open).toHaveBeenCalled(); - expect(mockToastService.showSuccess).toHaveBeenCalledWith('registries.justification.decisionRecorded'); + expect(toastService.showSuccess).toHaveBeenCalledWith('registries.justification.decisionRecorded'); }); - it('should delete draft update after confirmation', () => { - const mockActions = { - deleteSchemaResponse: jest.fn().mockReturnValue(of({})), - clearState: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: mockActions }); + it('should dispatch deleteSchemaResponse and clearState after confirmation', () => { + (store.dispatch as jest.Mock).mockClear(); component.deleteDraftUpdate(); - expect(mockCustomConfirmationService.confirmDelete).toHaveBeenCalled(); - const call = (mockCustomConfirmationService.confirmDelete as any).mock.calls[0][0]; + + expect(customConfirmationService.confirmDelete).toHaveBeenCalled(); + const call = customConfirmationService.confirmDelete.mock.calls[0][0]; call.onConfirm(); - expect(mockActions.deleteSchemaResponse).toHaveBeenCalledWith('rev-1'); - expect(mockToastService.showSuccess).toHaveBeenCalledWith('registries.justification.successDeleteDraft'); - expect(mockActions.clearState).toHaveBeenCalled(); + expect(store.dispatch).toHaveBeenCalledWith(new DeleteSchemaResponse('rev-1')); + expect(toastService.showSuccess).toHaveBeenCalledWith('registries.justification.successDeleteDraft'); + expect(store.dispatch).toHaveBeenCalledWith(new ClearState()); expect(mockRouter.navigateByUrl).toHaveBeenCalledWith('/reg-1/overview'); }); }); diff --git a/src/app/features/registries/components/justification-review/justification-review.component.ts b/src/app/features/registries/components/justification-review/justification-review.component.ts index 26cb214f7..050fc1fa1 100644 --- a/src/app/features/registries/components/justification-review/justification-review.component.ts +++ b/src/app/features/registries/components/justification-review/justification-review.component.ts @@ -6,12 +6,14 @@ import { Button } from 'primeng/button'; import { Card } from 'primeng/card'; import { Message } from 'primeng/message'; -import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core'; +import { filter } from 'rxjs'; + +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { ActivatedRoute, Router } from '@angular/router'; import { RegistrationBlocksDataComponent } from '@osf/shared/components/registration-blocks-data/registration-blocks-data.component'; import { INPUT_VALIDATION_MESSAGES } from '@osf/shared/constants/input-validation-messages.const'; -import { FieldType } from '@osf/shared/enums/field-type.enum'; import { RevisionReviewStates } from '@osf/shared/enums/revision-review-states.enum'; import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { CustomDialogService } from '@osf/shared/services/custom-dialog.service'; @@ -34,6 +36,7 @@ export class JustificationReviewComponent { private readonly customConfirmationService = inject(CustomConfirmationService); private readonly customDialogService = inject(CustomDialogService); private readonly toastService = inject(ToastService); + private readonly destroyRef = inject(DestroyRef); readonly pages = select(RegistriesSelectors.getPagesSchema); readonly schemaResponse = select(RegistriesSelectors.getSchemaResponse); @@ -42,10 +45,8 @@ export class JustificationReviewComponent { readonly isSchemaResponseLoading = select(RegistriesSelectors.getSchemaResponseLoading); readonly INPUT_VALIDATION_MESSAGES = INPUT_VALIDATION_MESSAGES; - readonly FieldType = FieldType; - readonly RevisionReviewStates = RevisionReviewStates; - actions = createDispatchMap({ + private readonly actions = createDispatchMap({ deleteSchemaResponse: DeleteSchemaResponse, handleSchemaResponse: HandleSchemaResponse, clearState: ClearState, @@ -53,50 +54,27 @@ export class JustificationReviewComponent { private readonly revisionId = this.route.snapshot.params['id']; - get isUnapproved() { - return this.schemaResponse()?.reviewsState === RevisionReviewStates.Unapproved; - } - - get inProgress() { - return this.schemaResponse()?.reviewsState === RevisionReviewStates.RevisionInProgress; - } + readonly isUnapproved = computed(() => this.schemaResponse()?.reviewsState === RevisionReviewStates.Unapproved); + readonly inProgress = computed(() => this.schemaResponse()?.reviewsState === RevisionReviewStates.RevisionInProgress); changes = computed(() => { - let questions: Record = {}; - this.pages().forEach((page) => { - if (page.sections?.length) { - questions = { - ...questions, - ...Object.fromEntries( - page.sections.flatMap( - (section) => section.questions?.map((q) => [q.responseKey, q.displayText || '']) || [] - ) - ), - }; - } else { - questions = { - ...questions, - ...Object.fromEntries(page.questions?.map((q) => [q.responseKey, q.displayText]) || []), - }; - } - }); - const updatedFields = this.updatedFields(); + const questions = this.buildQuestionMap(); const updatedResponseKeys = this.schemaResponse()?.updatedResponseKeys || []; - const uniqueKeys = new Set([...updatedResponseKeys, ...Object.keys(updatedFields)]); + const uniqueKeys = new Set([...updatedResponseKeys, ...Object.keys(this.updatedFields())]); return Array.from(uniqueKeys).map((key) => questions[key]); }); submit(): void { - this.actions.handleSchemaResponse(this.revisionId, SchemaActionTrigger.Submit).subscribe({ - next: () => { + this.actions + .handleSchemaResponse(this.revisionId, SchemaActionTrigger.Submit) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { this.toastService.showSuccess('registries.justification.successSubmit'); - }, - }); + }); } goBack(): void { - const previousStep = this.pages().length; - this.router.navigate(['../', previousStep], { relativeTo: this.route }); + this.router.navigate(['../', this.pages().length], { relativeTo: this.route }); } deleteDraftUpdate() { @@ -105,24 +83,26 @@ export class JustificationReviewComponent { messageKey: 'registries.justification.confirmDeleteUpdate.message', onConfirm: () => { const registrationId = this.schemaResponse()?.registrationId || ''; - this.actions.deleteSchemaResponse(this.revisionId).subscribe({ - next: () => { + this.actions + .deleteSchemaResponse(this.revisionId) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { this.toastService.showSuccess('registries.justification.successDeleteDraft'); this.actions.clearState(); this.router.navigateByUrl(`/${registrationId}/overview`); - }, - }); + }); }, }); } acceptChanges() { - this.actions.handleSchemaResponse(this.revisionId, SchemaActionTrigger.Approve).subscribe({ - next: () => { + this.actions + .handleSchemaResponse(this.revisionId, SchemaActionTrigger.Approve) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { this.toastService.showSuccess('registries.justification.successAccept'); this.router.navigateByUrl(`/${this.schemaResponse()?.registrationId}/overview`); - }, - }); + }); } continueEditing() { @@ -130,14 +110,23 @@ export class JustificationReviewComponent { .open(ConfirmContinueEditingDialogComponent, { header: 'registries.justification.confirmContinueEditing.header', width: '552px', - data: { - revisionId: this.revisionId, - }, + data: { revisionId: this.revisionId }, }) - .onClose.subscribe((result) => { - if (result) { - this.toastService.showSuccess('registries.justification.decisionRecorded'); - } - }); + .onClose.pipe( + filter((result) => !!result), + takeUntilDestroyed(this.destroyRef) + ) + .subscribe(() => this.toastService.showSuccess('registries.justification.decisionRecorded')); + } + + private buildQuestionMap(): Record { + return Object.fromEntries( + this.pages().flatMap((page) => { + const questions = page.sections?.length + ? page.sections.flatMap((section) => section.questions || []) + : page.questions || []; + return questions.map((q) => [q.responseKey, q.displayText || '']); + }) + ); } } diff --git a/src/app/features/registries/components/justification-step/justification-step.component.html b/src/app/features/registries/components/justification-step/justification-step.component.html index e1265453e..7b3be3e89 100644 --- a/src/app/features/registries/components/justification-step/justification-step.component.html +++ b/src/app/features/registries/components/justification-step/justification-step.component.html @@ -12,7 +12,7 @@

{{ 'registries.justification.title' | translate }}

pTextarea formControlName="justification" > - @if (isJustificationValid) { + @if (showJustificationError) { {{ INPUT_VALIDATION_MESSAGES.required | translate }} @@ -25,7 +25,7 @@

{{ 'registries.justification.title' | translate }}

diff --git a/src/app/features/registries/components/justification-step/justification-step.component.spec.ts b/src/app/features/registries/components/justification-step/justification-step.component.spec.ts index c3b98e705..5e7c73b47 100644 --- a/src/app/features/registries/components/justification-step/justification-step.component.spec.ts +++ b/src/app/features/registries/components/justification-step/justification-step.component.spec.ts @@ -1,57 +1,67 @@ -import { MockProvider } from 'ng-mocks'; +import { Store } from '@ngxs/store'; -import { of } from 'rxjs'; +import { MockProvider } from 'ng-mocks'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ActivatedRoute, Router } from '@angular/router'; -import { RegistriesSelectors } from '@osf/features/registries/store'; +import { + ClearState, + DeleteSchemaResponse, + RegistriesSelectors, + UpdateSchemaResponse, + UpdateStepState, +} from '@osf/features/registries/store'; +import { SchemaResponse } from '@osf/shared/models/registration/schema-response.model'; import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { ToastService } from '@osf/shared/services/toast.service'; import { JustificationStepComponent } from './justification-step.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { CustomConfirmationServiceMockBuilder } from '@testing/providers/custom-confirmation-provider.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; +import { + CustomConfirmationServiceMock, + CustomConfirmationServiceMockType, +} from '@testing/providers/custom-confirmation-provider.mock'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; -import { ToastServiceMockBuilder } from '@testing/providers/toast-provider.mock'; +import { ToastServiceMock, ToastServiceMockType } from '@testing/providers/toast-provider.mock'; describe('JustificationStepComponent', () => { let component: JustificationStepComponent; let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; - let mockRouter: jest.Mocked; - let mockCustomConfirmationService: ReturnType; - let mockToastService: ReturnType; + let store: Store; + let mockRouter: RouterMockType; + let toastService: ToastServiceMockType; + let customConfirmationService: CustomConfirmationServiceMockType; - const MOCK_SCHEMA_RESPONSE = { + const MOCK_SCHEMA_RESPONSE: Partial = { registrationId: 'reg-1', revisionJustification: 'reason', - } as any; + }; - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'rev-1' }).build(); - mockRouter = { navigate: jest.fn(), navigateByUrl: jest.fn(), url: '/x' } as any; - mockCustomConfirmationService = CustomConfirmationServiceMockBuilder.create().build(); - mockToastService = ToastServiceMockBuilder.create().build(); + beforeEach(() => { + const mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'rev-1' }).build(); + mockRouter = RouterMockBuilder.create().withUrl('/x').build(); + toastService = ToastServiceMock.simple(); + customConfirmationService = CustomConfirmationServiceMock.simple(); - await TestBed.configureTestingModule({ - imports: [JustificationStepComponent, OSFTestingModule], + TestBed.configureTestingModule({ + imports: [JustificationStepComponent], providers: [ + provideOSFCore(), + MockProvider(ToastService, toastService), MockProvider(ActivatedRoute, mockActivatedRoute), MockProvider(Router, mockRouter), - MockProvider(CustomConfirmationService, mockCustomConfirmationService as any), - MockProvider(ToastService, mockToastService), + MockProvider(CustomConfirmationService, customConfirmationService), provideMockStore({ - signals: [ - { selector: RegistriesSelectors.getSchemaResponse, value: MOCK_SCHEMA_RESPONSE }, - { selector: RegistriesSelectors.getStepsState, value: {} }, - ], + signals: [{ selector: RegistriesSelectors.getSchemaResponse, value: MOCK_SCHEMA_RESPONSE }], }), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(JustificationStepComponent); component = fixture.componentInstance; fixture.detectChanges(); @@ -66,16 +76,12 @@ describe('JustificationStepComponent', () => { }); it('should submit justification and navigate to first step', () => { - const mockActions = { - updateRevision: jest.fn().mockReturnValue(of({})), - updateStepState: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: mockActions }); - component.justificationForm.patchValue({ justification: 'new reason' }); + (store.dispatch as jest.Mock).mockClear(); + component.submit(); - expect(mockActions.updateRevision).toHaveBeenCalledWith('rev-1', 'new reason'); + expect(store.dispatch).toHaveBeenCalledWith(new UpdateSchemaResponse('rev-1', 'new reason')); expect(mockRouter.navigate).toHaveBeenCalledWith(['../1'], { relativeTo: expect.any(Object), onSameUrlNavigation: 'reload', @@ -83,21 +89,36 @@ describe('JustificationStepComponent', () => { }); it('should delete draft update after confirmation', () => { - const mockActions = { - deleteSchemaResponse: jest.fn().mockReturnValue(of({})), - clearState: jest.fn(), - } as any; - Object.defineProperty(component, 'actions', { value: mockActions }); + (store.dispatch as jest.Mock).mockClear(); component.deleteDraftUpdate(); - expect(mockCustomConfirmationService.confirmDelete).toHaveBeenCalled(); - const call = (mockCustomConfirmationService.confirmDelete as any).mock.calls[0][0]; + expect(customConfirmationService.confirmDelete).toHaveBeenCalled(); + const call = customConfirmationService.confirmDelete.mock.calls[0][0]; call.onConfirm(); - expect(mockActions.deleteSchemaResponse).toHaveBeenCalledWith('rev-1'); - expect(mockToastService.showSuccess).toHaveBeenCalledWith('registries.justification.successDeleteDraft'); - expect(mockActions.clearState).toHaveBeenCalled(); + expect(store.dispatch).toHaveBeenCalledWith(new DeleteSchemaResponse('rev-1')); + expect(toastService.showSuccess).toHaveBeenCalledWith('registries.justification.successDeleteDraft'); + expect(store.dispatch).toHaveBeenCalledWith(new ClearState()); expect(mockRouter.navigateByUrl).toHaveBeenCalledWith('/reg-1/overview'); }); + + it('should dispatch updateStepState and updateRevision on destroy when form changed', () => { + component.justificationForm.patchValue({ justification: 'changed reason' }); + (store.dispatch as jest.Mock).mockClear(); + + component.ngOnDestroy(); + + expect(store.dispatch).toHaveBeenCalledWith(new UpdateStepState('0', false, true)); + expect(store.dispatch).toHaveBeenCalledWith(new UpdateSchemaResponse('rev-1', 'changed reason')); + }); + + it('should not dispatch updateRevision on destroy when form is unchanged', () => { + (store.dispatch as jest.Mock).mockClear(); + + component.ngOnDestroy(); + + expect(store.dispatch).toHaveBeenCalledWith(new UpdateStepState('0', false, true)); + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(UpdateSchemaResponse)); + }); }); diff --git a/src/app/features/registries/components/justification-step/justification-step.component.ts b/src/app/features/registries/components/justification-step/justification-step.component.ts index eee067b61..0ba540a0f 100644 --- a/src/app/features/registries/components/justification-step/justification-step.component.ts +++ b/src/app/features/registries/components/justification-step/justification-step.component.ts @@ -6,9 +6,10 @@ import { Button } from 'primeng/button'; import { Message } from 'primeng/message'; import { Textarea } from 'primeng/textarea'; -import { tap } from 'rxjs'; +import { filter, take } from 'rxjs'; -import { ChangeDetectionStrategy, Component, effect, inject, OnDestroy } from '@angular/core'; +import { ChangeDetectionStrategy, Component, DestroyRef, inject, OnDestroy, signal } from '@angular/core'; +import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; @@ -40,13 +41,13 @@ export class JustificationStepComponent implements OnDestroy { private readonly router = inject(Router); private readonly customConfirmationService = inject(CustomConfirmationService); private readonly toastService = inject(ToastService); + private readonly destroyRef = inject(DestroyRef); readonly schemaResponse = select(RegistriesSelectors.getSchemaResponse); - readonly stepsState = select(RegistriesSelectors.getStepsState); readonly INPUT_VALIDATION_MESSAGES = INPUT_VALIDATION_MESSAGES; - actions = createDispatchMap({ + private readonly actions = createDispatchMap({ updateStepState: UpdateStepState, updateRevision: UpdateSchemaResponse, deleteSchemaResponse: DeleteSchemaResponse, @@ -54,40 +55,51 @@ export class JustificationStepComponent implements OnDestroy { }); private readonly revisionId = this.route.snapshot.params['id']; + private readonly isDraftDeleted = signal(false); - justificationForm = this.fb.group({ + readonly justificationForm = this.fb.group({ justification: ['', [Validators.maxLength(InputLimits.description.maxLength), CustomValidators.requiredTrimmed()]], }); - get isJustificationValid(): boolean { + get showJustificationError(): boolean { const control = this.justificationForm.controls['justification']; return control.errors?.['required'] && (control.touched || control.dirty); } - isDraftDeleted = false; - constructor() { - effect(() => { - const revisionJustification = this.schemaResponse()?.revisionJustification; - if (revisionJustification) { - this.justificationForm.patchValue({ justification: revisionJustification }); - } - }); + this.setupInitialJustification(); + } + + ngOnDestroy(): void { + if (this.isDraftDeleted()) { + return; + } + + this.actions.updateStepState('0', this.justificationForm.invalid, true); + + const changes = findChangedFields( + { justification: this.justificationForm.value.justification! }, + { justification: this.schemaResponse()?.revisionJustification } + ); + + if (Object.keys(changes).length > 0) { + this.actions.updateRevision(this.revisionId, this.justificationForm.value.justification!); + } + + this.justificationForm.markAllAsTouched(); } submit(): void { this.actions .updateRevision(this.revisionId, this.justificationForm.value.justification!) - .pipe( - tap(() => { - this.justificationForm.markAllAsTouched(); - this.router.navigate(['../1'], { - relativeTo: this.route, - onSameUrlNavigation: 'reload', - }); - }) - ) - .subscribe(); + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { + this.justificationForm.markAllAsTouched(); + this.router.navigate(['../1'], { + relativeTo: this.route, + onSameUrlNavigation: 'reload', + }); + }); } deleteDraftUpdate() { @@ -96,29 +108,25 @@ export class JustificationStepComponent implements OnDestroy { messageKey: 'registries.justification.confirmDeleteUpdate.message', onConfirm: () => { const registrationId = this.schemaResponse()?.registrationId || ''; - this.actions.deleteSchemaResponse(this.revisionId).subscribe({ - next: () => { - this.isDraftDeleted = true; + this.actions + .deleteSchemaResponse(this.revisionId) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { + this.isDraftDeleted.set(true); this.actions.clearState(); this.toastService.showSuccess('registries.justification.successDeleteDraft'); this.router.navigateByUrl(`/${registrationId}/overview`); - }, - }); + }); }, }); } - ngOnDestroy(): void { - if (!this.isDraftDeleted) { - this.actions.updateStepState('0', this.justificationForm.invalid, true); - const changes = findChangedFields( - { justification: this.justificationForm.value.justification! }, - { justification: this.schemaResponse()?.revisionJustification } - ); - if (Object.keys(changes).length > 0) { - this.actions.updateRevision(this.revisionId, this.justificationForm.value.justification!); - } - this.justificationForm.markAllAsTouched(); - } + private setupInitialJustification() { + toObservable(this.schemaResponse) + .pipe( + filter((response) => !!response?.revisionJustification), + take(1) + ) + .subscribe((response) => this.justificationForm.patchValue({ justification: response!.revisionJustification })); } } diff --git a/src/app/features/registries/components/new-registration/new-registration.component.html b/src/app/features/registries/components/new-registration/new-registration.component.html index 8ce2cb21f..7c46cb5e9 100644 --- a/src/app/features/registries/components/new-registration/new-registration.component.html +++ b/src/app/features/registries/components/new-registration/new-registration.component.html @@ -16,25 +16,25 @@

{{ 'registries.new.steps.title' | translate }} 1

- @if (fromProject) { + @if (fromProject()) {

{{ 'registries.new.steps.title' | translate }} 2

{{ 'registries.new.steps.step2' | translate }}

@@ -49,7 +49,6 @@

{{ 'registries.new.steps.title' | translate }} 2

optionValue="id" filter="true" [loading]="isProjectsLoading()" - (onChange)="onSelectProject($event.value)" (onFilter)="onProjectFilter($event.filter)" class="w-6" /> @@ -58,7 +57,7 @@

{{ 'registries.new.steps.title' | translate }} 2

} -

{{ 'registries.new.steps.title' | translate }} {{ fromProject ? '3' : '2' }}

+

{{ 'registries.new.steps.title' | translate }} {{ fromProject() ? '3' : '2' }}

{{ 'registries.new.steps.step3' | translate }}

{{ 'registries.new.steps.title' | translate }} {{ fromProject ? optionLabel="name" optionValue="id" [loading]="isProvidersLoading()" - (onChange)="onSelectProviderSchema($event.value)" class="w-6" />
diff --git a/src/app/features/registries/components/new-registration/new-registration.component.spec.ts b/src/app/features/registries/components/new-registration/new-registration.component.spec.ts index ff8f9c3ee..c06634a3a 100644 --- a/src/app/features/registries/components/new-registration/new-registration.component.spec.ts +++ b/src/app/features/registries/components/new-registration/new-registration.component.spec.ts @@ -1,46 +1,48 @@ -import { MockComponent, MockProvider } from 'ng-mocks'; +import { Store } from '@ngxs/store'; -import { of } from 'rxjs'; +import { MockComponent, MockProvider } from 'ng-mocks'; -import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ActivatedRoute, Router } from '@angular/router'; import { UserSelectors } from '@core/store/user'; -import { RegistriesSelectors } from '@osf/features/registries/store'; +import { CreateDraft, GetProjects, GetProviderSchemas, RegistriesSelectors } from '@osf/features/registries/store'; import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header.component'; +import { ToastService } from '@osf/shared/services/toast.service'; +import { GetRegistryProvider } from '@shared/stores/registration-provider'; import { NewRegistrationComponent } from './new-registration.component'; import { MOCK_PROVIDER_SCHEMAS } from '@testing/mocks/registries.mock'; -import { OSFTestingModule } from '@testing/osf.testing.module'; +import { provideOSFCore } from '@testing/osf.testing.provider'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; -import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('NewRegistrationComponent', () => { let component: NewRegistrationComponent; let fixture: ComponentFixture; - let mockActivatedRoute: ReturnType; - let mockRouter: ReturnType; - const PROJECTS = [{ id: 'p1', title: 'P1' }]; - const PROVIDER_SCHEMAS = MOCK_PROVIDER_SCHEMAS; + let store: Store; + let mockRouter: RouterMockType; - beforeEach(async () => { - mockActivatedRoute = ActivatedRouteMockBuilder.create() + beforeEach(() => { + const mockActivatedRoute = ActivatedRouteMockBuilder.create() .withParams({ providerId: 'prov-1' }) .withQueryParams({ projectId: 'proj-1' }) .build(); mockRouter = RouterMockBuilder.create().withUrl('/x').build(); - await TestBed.configureTestingModule({ - imports: [NewRegistrationComponent, OSFTestingModule, MockComponent(SubHeaderComponent)], + TestBed.configureTestingModule({ + imports: [NewRegistrationComponent, MockComponent(SubHeaderComponent)], providers: [ + provideOSFCore(), MockProvider(ActivatedRoute, mockActivatedRoute), + MockProvider(ToastService), MockProvider(Router, mockRouter), provideMockStore({ signals: [ - { selector: RegistriesSelectors.getProjects, value: PROJECTS }, - { selector: RegistriesSelectors.getProviderSchemas, value: PROVIDER_SCHEMAS }, + { selector: RegistriesSelectors.getProjects, value: [{ id: 'p1', title: 'P1' }] }, + { selector: RegistriesSelectors.getProviderSchemas, value: MOCK_PROVIDER_SCHEMAS }, { selector: RegistriesSelectors.isDraftSubmitting, value: false }, { selector: RegistriesSelectors.getDraftRegistration, value: { id: 'draft-1' } }, { selector: RegistriesSelectors.isProvidersLoading, value: false }, @@ -49,8 +51,9 @@ describe('NewRegistrationComponent', () => { ], }), ], - }).compileComponents(); + }); + store = TestBed.inject(Store); fixture = TestBed.createComponent(NewRegistrationComponent); component = fixture.componentInstance; fixture.detectChanges(); @@ -60,44 +63,92 @@ describe('NewRegistrationComponent', () => { expect(component).toBeTruthy(); }); - it('should init with provider and project ids from route', () => { - expect(component.providerId).toBe('prov-1'); - expect(component.projectId).toBe('proj-1'); - expect(component.fromProject).toBe(true); + it('should dispatch initial data fetching on init', () => { + expect(store.dispatch).toHaveBeenCalledWith(new GetProjects('user-1', '')); + expect(store.dispatch).toHaveBeenCalledWith(new GetRegistryProvider('prov-1')); + expect(store.dispatch).toHaveBeenCalledWith(new GetProviderSchemas('prov-1')); }); - it('should default providerSchema when empty', () => { - expect(component['draftForm'].get('providerSchema')?.value).toBe('schema-1'); + it('should init fromProject as true when projectId is present', () => { + expect(component.fromProject()).toBe(true); }); - it('should update project on selection', () => { - component.onSelectProject('p1'); - expect(component['draftForm'].get('project')?.value).toBe('p1'); + it('should init form with project id from route', () => { + expect(component.draftForm.get('project')?.value).toBe('proj-1'); + }); + + it('should default providerSchema when schemas are available', () => { + expect(component.draftForm.get('providerSchema')?.value).toBe('schema-1'); }); it('should toggle fromProject and add/remove validator', () => { - component.fromProject = false; + component.fromProject.set(false); component.toggleFromProject(); - expect(component.fromProject).toBe(true); + expect(component.fromProject()).toBe(true); + expect(component.draftForm.get('project')?.validator).toBeTruthy(); + component.toggleFromProject(); - expect(component.fromProject).toBe(false); + expect(component.fromProject()).toBe(false); + expect(component.draftForm.get('project')?.validator).toBeNull(); }); - it('should create draft when form valid', () => { - const mockActions = { - createDraft: jest.fn().mockReturnValue(of({})), - } as any; - Object.defineProperty(component, 'actions', { value: mockActions }); - + it('should dispatch createDraft and navigate when form is valid', () => { component.draftForm.patchValue({ providerSchema: 'schema-1', project: 'proj-1' }); - component.fromProject = true; + component.fromProject.set(true); + (store.dispatch as jest.Mock).mockClear(); + component.createDraft(); - expect(mockActions.createDraft).toHaveBeenCalledWith({ - registrationSchemaId: 'schema-1', - provider: 'prov-1', - projectId: 'proj-1', - }); + expect(store.dispatch).toHaveBeenCalledWith( + new CreateDraft({ registrationSchemaId: 'schema-1', provider: 'prov-1', projectId: 'proj-1' }) + ); expect(mockRouter.navigate).toHaveBeenCalledWith(['/registries/drafts/', 'draft-1', 'metadata']); }); + + it('should not dispatch createDraft when form is invalid', () => { + component.draftForm.patchValue({ providerSchema: '' }); + (store.dispatch as jest.Mock).mockClear(); + + component.createDraft(); + + expect(store.dispatch).not.toHaveBeenCalledWith(expect.any(CreateDraft)); + }); + + it('should dispatch getProjects after debounced filter', fakeAsync(() => { + (store.dispatch as jest.Mock).mockClear(); + + component.onProjectFilter('abc'); + tick(300); + + expect(store.dispatch).toHaveBeenCalledWith(new GetProjects('user-1', 'abc')); + })); + + it('should not dispatch duplicate getProjects for same filter value', fakeAsync(() => { + (store.dispatch as jest.Mock).mockClear(); + + component.onProjectFilter('abc'); + tick(300); + component.onProjectFilter('abc'); + tick(300); + + const getProjectsCalls = (store.dispatch as jest.Mock).mock.calls.filter( + ([action]: [any]) => action instanceof GetProjects + ); + expect(getProjectsCalls.length).toBe(1); + })); + + it('should debounce rapid filter calls and dispatch only the last value', fakeAsync(() => { + (store.dispatch as jest.Mock).mockClear(); + + component.onProjectFilter('a'); + component.onProjectFilter('ab'); + component.onProjectFilter('abc'); + tick(300); + + const getProjectsCalls = (store.dispatch as jest.Mock).mock.calls.filter( + ([action]: [any]) => action instanceof GetProjects + ); + expect(getProjectsCalls.length).toBe(1); + expect(getProjectsCalls[0][0]).toEqual(new GetProjects('user-1', 'abc')); + })); }); diff --git a/src/app/features/registries/components/new-registration/new-registration.component.ts b/src/app/features/registries/components/new-registration/new-registration.component.ts index 952ee73f8..62e4b8e61 100644 --- a/src/app/features/registries/components/new-registration/new-registration.component.ts +++ b/src/app/features/registries/components/new-registration/new-registration.component.ts @@ -6,10 +6,10 @@ import { Button } from 'primeng/button'; import { Card } from 'primeng/card'; import { Select } from 'primeng/select'; -import { debounceTime, distinctUntilChanged, Subject } from 'rxjs'; +import { debounceTime, distinctUntilChanged, filter, Subject, take } from 'rxjs'; -import { ChangeDetectionStrategy, Component, DestroyRef, effect, inject } from '@angular/core'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { ChangeDetectionStrategy, Component, DestroyRef, inject, signal } from '@angular/core'; +import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; @@ -32,93 +32,95 @@ export class NewRegistrationComponent { private readonly toastService = inject(ToastService); private readonly router = inject(Router); private readonly route = inject(ActivatedRoute); - private destroyRef = inject(DestroyRef); + private readonly destroyRef = inject(DestroyRef); + readonly user = select(UserSelectors.getCurrentUser); readonly projects = select(RegistriesSelectors.getProjects); readonly providerSchemas = select(RegistriesSelectors.getProviderSchemas); readonly isDraftSubmitting = select(RegistriesSelectors.isDraftSubmitting); - readonly draftRegistration = select(RegistriesSelectors.getDraftRegistration); readonly isProvidersLoading = select(RegistriesSelectors.isProvidersLoading); readonly isProjectsLoading = select(RegistriesSelectors.isProjectsLoading); - readonly user = select(UserSelectors.getCurrentUser); - actions = createDispatchMap({ + private readonly draftRegistration = select(RegistriesSelectors.getDraftRegistration); + + private readonly actions = createDispatchMap({ getProvider: GetRegistryProvider, getProjects: GetProjects, getProviderSchemas: GetProviderSchemas, createDraft: CreateDraft, }); + private readonly providerId = this.route.snapshot.params['providerId']; + private readonly projectId = this.route.snapshot.queryParams['projectId']; + private readonly filter$ = new Subject(); - readonly providerId = this.route.snapshot.params['providerId']; - readonly projectId = this.route.snapshot.queryParams['projectId']; - - fromProject = this.projectId !== undefined; - - draftForm = this.fb.group({ + readonly fromProject = signal(this.projectId !== undefined); + readonly draftForm = this.fb.group({ providerSchema: ['', Validators.required], project: [this.projectId || ''], }); - private filter$ = new Subject(); - constructor() { - const userId = this.user()?.id; - if (userId) { - this.actions.getProjects(userId, ''); - } - this.actions.getProvider(this.providerId); - this.actions.getProviderSchemas(this.providerId); - effect(() => { - const providerSchema = this.draftForm.get('providerSchema')?.value; - if (!providerSchema) { - this.draftForm.get('providerSchema')?.setValue(this.providerSchemas()[0]?.id); - } - }); - - this.filter$ - .pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed(this.destroyRef)) - .subscribe((value: string) => { - if (userId) { - this.actions.getProjects(userId, value); - } - }); - } - - onSelectProject(projectId: string) { - this.draftForm.patchValue({ - project: projectId, - }); + this.loadInitialData(); + this.setupDefaultSchema(); + this.setupProjectFilter(); } onProjectFilter(value: string) { this.filter$.next(value); } - onSelectProviderSchema(providerSchemaId: string) { - this.draftForm.patchValue({ - providerSchema: providerSchemaId, - }); - } - toggleFromProject() { - this.fromProject = !this.fromProject; - this.draftForm.get('project')?.setValidators(this.fromProject ? Validators.required : null); - this.draftForm.get('project')?.updateValueAndValidity(); + this.fromProject.update((v) => !v); + const projectControl = this.draftForm.get('project'); + projectControl?.setValidators(this.fromProject() ? Validators.required : null); + projectControl?.updateValueAndValidity(); } createDraft() { + if (this.draftForm.invalid) { + return; + } + const { providerSchema, project } = this.draftForm.value; - if (this.draftForm.valid) { - this.actions - .createDraft({ - registrationSchemaId: providerSchema!, - provider: this.providerId, - projectId: this.fromProject ? (project ?? undefined) : undefined, - }) - .subscribe(() => { - this.toastService.showSuccess('registries.new.createdSuccessfully'); - this.router.navigate(['/registries/drafts/', this.draftRegistration()?.id, 'metadata']); - }); + this.actions + .createDraft({ + registrationSchemaId: providerSchema!, + provider: this.providerId, + projectId: this.fromProject() ? (project ?? undefined) : undefined, + }) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { + this.toastService.showSuccess('registries.new.createdSuccessfully'); + this.router.navigate(['/registries/drafts/', this.draftRegistration()!.id, 'metadata']); + }); + } + + private loadInitialData() { + const userId = this.user()?.id; + if (userId) { + this.actions.getProjects(userId, ''); } + this.actions.getProvider(this.providerId); + this.actions.getProviderSchemas(this.providerId); + } + + private setupDefaultSchema() { + toObservable(this.providerSchemas) + .pipe( + filter((schemas) => schemas.length > 0), + take(1) + ) + .subscribe((schemas) => this.draftForm.get('providerSchema')?.setValue(schemas[0].id)); + } + + private setupProjectFilter() { + this.filter$ + .pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed(this.destroyRef)) + .subscribe((value: string) => { + const currentUserId = this.user()?.id; + if (currentUserId) { + this.actions.getProjects(currentUserId, value); + } + }); } } diff --git a/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.spec.ts b/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.spec.ts index 551d5a24d..4cc42b958 100644 --- a/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.spec.ts +++ b/src/app/features/registries/components/registries-metadata-step/registries-metadata-step.component.spec.ts @@ -1,13 +1,15 @@ import { Store } from '@ngxs/store'; -import { MockComponents, MockModule, ngMocks } from 'ng-mocks'; +import { MockComponents, MockModule, MockProvider, ngMocks } from 'ng-mocks'; import { TextareaModule } from 'primeng/textarea'; import { signal, WritableSignal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute, Router } from '@angular/router'; import { TextInputComponent } from '@osf/shared/components/text-input/text-input.component'; +import { CustomConfirmationService } from '@osf/shared/services/custom-confirmation.service'; import { ContributorsSelectors } from '@osf/shared/stores/contributors'; import { SubjectsSelectors } from '@osf/shared/stores/subjects'; @@ -20,14 +22,14 @@ import { RegistriesSubjectsComponent } from './registries-subjects/registries-su import { RegistriesTagsComponent } from './registries-tags/registries-tags.component'; import { RegistriesMetadataStepComponent } from './registries-metadata-step.component'; -import { - CustomConfirmationServiceMock, - MockCustomConfirmationServiceProvider, -} from '@testing/mocks/custom-confirmation.service.mock'; import { MOCK_DRAFT_REGISTRATION } from '@testing/mocks/draft-registration.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 { + CustomConfirmationServiceMock, + CustomConfirmationServiceMockType, +} from '@testing/providers/custom-confirmation-provider.mock'; +import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('RegistriesMetadataStepComponent', () => { @@ -38,6 +40,7 @@ describe('RegistriesMetadataStepComponent', () => { let store: Store; let mockRouter: RouterMockType; let stepsStateSignal: WritableSignal<{ invalid: boolean }[]>; + let customConfirmationService: CustomConfirmationServiceMockType; const mockDraft = { ...MOCK_DRAFT_REGISTRATION, title: 'Test Title', description: 'Test Description' }; @@ -45,6 +48,7 @@ describe('RegistriesMetadataStepComponent', () => { 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 }]); + customConfirmationService = CustomConfirmationServiceMock.simple(); TestBed.configureTestingModule({ imports: [ @@ -61,9 +65,9 @@ describe('RegistriesMetadataStepComponent', () => { ], providers: [ provideOSFCore(), - provideActivatedRouteMock(mockActivatedRoute), - provideRouterMock(mockRouter), - MockCustomConfirmationServiceProvider, + MockProvider(ActivatedRoute, mockActivatedRoute), + MockProvider(Router, mockRouter), + MockProvider(CustomConfirmationService, customConfirmationService), provideMockStore({ signals: [ { selector: RegistriesSelectors.getDraftRegistration, value: mockDraft }, @@ -128,7 +132,7 @@ describe('RegistriesMetadataStepComponent', () => { it('should call confirmDelete when deleteDraft is called', () => { component.deleteDraft(); - expect(CustomConfirmationServiceMock.confirmDelete).toHaveBeenCalledWith( + expect(customConfirmationService.confirmDelete).toHaveBeenCalledWith( expect.objectContaining({ headerKey: 'registries.deleteDraft', messageKey: 'registries.confirmDeleteDraft', @@ -137,7 +141,7 @@ describe('RegistriesMetadataStepComponent', () => { }); it('should set isDraftDeleted and navigate on deleteDraft confirm', () => { - CustomConfirmationServiceMock.confirmDelete.mockImplementation(({ onConfirm }: any) => onConfirm()); + customConfirmationService.confirmDelete.mockImplementation(({ onConfirm }: any) => onConfirm()); (store.dispatch as jest.Mock).mockClear(); component.deleteDraft(); diff --git a/src/app/features/registries/components/registry-provider-hero/registry-provider-hero.component.spec.ts b/src/app/features/registries/components/registry-provider-hero/registry-provider-hero.component.spec.ts index dd8165953..bc9d6e446 100644 --- a/src/app/features/registries/components/registry-provider-hero/registry-provider-hero.component.spec.ts +++ b/src/app/features/registries/components/registry-provider-hero/registry-provider-hero.component.spec.ts @@ -4,31 +4,58 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { Router } from '@angular/router'; import { SearchInputComponent } from '@osf/shared/components/search-input/search-input.component'; +import { BrandService } from '@osf/shared/services/brand.service'; import { CustomDialogService } from '@osf/shared/services/custom-dialog.service'; +import { HeaderStyleService } from '@osf/shared/services/header-style.service'; +import { RegistryProviderDetails } from '@shared/models/provider/registry-provider.model'; import { RegistryProviderHeroComponent } from './registry-provider-hero.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; -import { CustomDialogServiceMockBuilder } from '@testing/providers/custom-dialog-provider.mock'; -import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; +import { + CustomDialogServiceMockBuilder, + CustomDialogServiceMockType, +} from '@testing/providers/custom-dialog-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; describe('RegistryProviderHeroComponent', () => { let component: RegistryProviderHeroComponent; let fixture: ComponentFixture; - let mockCustomDialogService: ReturnType; + let mockRouter: RouterMockType; + let mockDialog: CustomDialogServiceMockType; + let mockBrandService: { applyBranding: jest.Mock; resetBranding: jest.Mock }; + let mockHeaderStyleService: { applyHeaderStyles: jest.Mock; resetToDefaults: jest.Mock }; - beforeEach(async () => { - const mockRouter = RouterMockBuilder.create().withUrl('/x').build(); - mockCustomDialogService = CustomDialogServiceMockBuilder.create().withDefaultOpen().build(); - await TestBed.configureTestingModule({ - imports: [RegistryProviderHeroComponent, OSFTestingModule, MockComponent(SearchInputComponent)], - providers: [MockProvider(Router, mockRouter), MockProvider(CustomDialogService, mockCustomDialogService)], - }).compileComponents(); + const mockProvider: RegistryProviderDetails = { + id: 'prov-1', + name: 'Provider', + descriptionHtml: '', + permissions: [], + brand: null, + iri: '', + reviewsWorkflow: '', + }; + + beforeEach(() => { + mockRouter = RouterMockBuilder.create().withUrl('/x').build(); + mockDialog = CustomDialogServiceMockBuilder.create().withDefaultOpen().build(); + mockBrandService = { applyBranding: jest.fn(), resetBranding: jest.fn() }; + mockHeaderStyleService = { applyHeaderStyles: jest.fn(), resetToDefaults: jest.fn() }; + + TestBed.configureTestingModule({ + imports: [RegistryProviderHeroComponent, MockComponent(SearchInputComponent)], + providers: [ + provideOSFCore(), + MockProvider(Router, mockRouter), + MockProvider(CustomDialogService, mockDialog), + MockProvider(BrandService, mockBrandService), + MockProvider(HeaderStyleService, mockHeaderStyleService), + ], + }); fixture = TestBed.createComponent(RegistryProviderHeroComponent); component = fixture.componentInstance; - - fixture.componentRef.setInput('provider', { id: 'prov-1', title: 'Provider', brand: undefined } as any); + fixture.componentRef.setInput('provider', mockProvider); fixture.componentRef.setInput('isProviderLoading', false); fixture.detectChanges(); }); @@ -45,24 +72,47 @@ describe('RegistryProviderHeroComponent', () => { it('should open help dialog', () => { component.openHelpDialog(); - expect(mockCustomDialogService.open).toHaveBeenCalledWith(expect.any(Function), { + expect(mockDialog.open).toHaveBeenCalledWith(expect.any(Function), { header: 'preprints.helpDialog.header', }); }); it('should navigate to create page when provider id present', () => { - const router = TestBed.inject(Router); - const navSpy = jest.spyOn(router, 'navigate'); - fixture.componentRef.setInput('provider', { id: 'prov-1', title: 'Provider', brand: undefined } as any); component.navigateToCreatePage(); - expect(navSpy).toHaveBeenCalledWith(['/registries/prov-1/new']); + expect(mockRouter.navigate).toHaveBeenCalledWith(['/registries/prov-1/new']); }); it('should not navigate when provider id missing', () => { - const router = TestBed.inject(Router); - const navSpy = jest.spyOn(router, 'navigate'); - fixture.componentRef.setInput('provider', { id: undefined, title: 'Provider', brand: undefined } as any); + fixture.componentRef.setInput('provider', { ...mockProvider, id: undefined }); component.navigateToCreatePage(); - expect(navSpy).not.toHaveBeenCalled(); + expect(mockRouter.navigate).not.toHaveBeenCalled(); + }); + + it('should apply branding and header styles when provider has brand', () => { + const brand = { + primaryColor: '#111', + secondaryColor: '#222', + backgroundColor: '#333', + topNavLogoImageUrl: 'logo.png', + heroBackgroundImageUrl: 'hero.png', + }; + + fixture.componentRef.setInput('provider', { ...mockProvider, brand }); + fixture.detectChanges(); + + expect(mockBrandService.applyBranding).toHaveBeenCalledWith(brand); + expect(mockHeaderStyleService.applyHeaderStyles).toHaveBeenCalledWith('#ffffff', '#111', 'hero.png'); + }); + + it('should not apply branding when provider has no brand', () => { + expect(mockBrandService.applyBranding).not.toHaveBeenCalled(); + expect(mockHeaderStyleService.applyHeaderStyles).not.toHaveBeenCalled(); + }); + + it('should reset branding and header styles on destroy', () => { + component.ngOnDestroy(); + + expect(mockHeaderStyleService.resetToDefaults).toHaveBeenCalled(); + expect(mockBrandService.resetBranding).toHaveBeenCalled(); }); }); diff --git a/src/app/features/registries/components/registry-services/registry-services.component.spec.ts b/src/app/features/registries/components/registry-services/registry-services.component.spec.ts index bf13f3b1d..a5878279c 100644 --- a/src/app/features/registries/components/registry-services/registry-services.component.spec.ts +++ b/src/app/features/registries/components/registry-services/registry-services.component.spec.ts @@ -1,17 +1,21 @@ +import { MockProvider } from 'ng-mocks'; + import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; import { RegistryServicesComponent } from './registry-services.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; +import { provideOSFCore } from '@testing/osf.testing.provider'; describe('RegistryServicesComponent', () => { let component: RegistryServicesComponent; let fixture: ComponentFixture; - beforeEach(async () => { - await TestBed.configureTestingModule({ - imports: [RegistryServicesComponent, OSFTestingModule], - }).compileComponents(); + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [RegistryServicesComponent], + providers: [provideOSFCore(), MockProvider(ActivatedRoute)], + }); fixture = TestBed.createComponent(RegistryServicesComponent); component = fixture.componentInstance; diff --git a/src/app/features/registries/components/review/review.component.html b/src/app/features/registries/components/review/review.component.html index 2cd5eeba4..89eaa06cc 100644 --- a/src/app/features/registries/components/review/review.component.html +++ b/src/app/features/registries/components/review/review.component.html @@ -4,7 +4,7 @@

{{ 'navigation.metadata' | translate }}

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

-

{{ draftRegistration()?.title | fixSpecialChar }}

+

{{ draftRegistration()?.title }}

@if (!draftRegistration()?.title) {

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

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

@@ -16,7 +16,7 @@

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

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

-

{{ draftRegistration()?.description | fixSpecialChar }}

+

{{ draftRegistration()?.description }}

@if (!draftRegistration()?.description) {

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

@@ -120,13 +120,13 @@

{{ section.title }}

[label]="'common.buttons.back' | translate" severity="info" class="mr-2" - (click)="goBack()" + (onClick)="goBack()" > @@ -135,7 +135,7 @@

{{ section.title }}

data-test-goto-register [label]="'registries.review.register' | translate" [disabled]="registerButtonDisabled()" - (click)="confirmRegistration()" + (onClick)="confirmRegistration()" >
diff --git a/src/app/features/registries/components/review/review.component.spec.ts b/src/app/features/registries/components/review/review.component.spec.ts index 510605975..1771c7971 100644 --- a/src/app/features/registries/components/review/review.component.spec.ts +++ b/src/app/features/registries/components/review/review.component.spec.ts @@ -1,119 +1,435 @@ +import { Store } from '@ngxs/store'; + import { MockComponents, MockProvider } from 'ng-mocks'; -import { of } from 'rxjs'; +import { Subject } from 'rxjs'; -import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { TestBed } from '@angular/core/testing'; import { ActivatedRoute, Router } from '@angular/router'; -import { RegistriesSelectors } from '@osf/features/registries/store'; +import { + ClearState, + DeleteDraft, + FetchLicenses, + FetchProjectChildren, + RegistriesSelectors, +} from '@osf/features/registries/store'; import { ContributorsListComponent } from '@osf/shared/components/contributors-list/contributors-list.component'; import { LicenseDisplayComponent } from '@osf/shared/components/license-display/license-display.component'; import { RegistrationBlocksDataComponent } from '@osf/shared/components/registration-blocks-data/registration-blocks-data.component'; -import { FieldType } from '@osf/shared/enums/field-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'; -import { SubjectsSelectors } from '@osf/shared/stores/subjects'; +import { + ContributorsSelectors, + GetAllContributors, + LoadMoreContributors, + ResetContributorsState, +} from '@osf/shared/stores/contributors'; +import { FetchSelectedSubjects, SubjectsSelectors } from '@osf/shared/stores/subjects'; import { ReviewComponent } from './review.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 { provideOSFCore } from '@testing/osf.testing.provider'; +import { + CustomConfirmationServiceMock, + CustomConfirmationServiceMockType, +} from '@testing/providers/custom-confirmation-provider.mock'; +import { + CustomDialogServiceMockBuilder, + CustomDialogServiceMockType, +} from '@testing/providers/custom-dialog-provider.mock'; import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; -import { RouterMockBuilder } from '@testing/providers/router-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; -import { ToastServiceMockBuilder } from '@testing/providers/toast-provider.mock'; +import { ToastServiceMock, ToastServiceMockType } from '@testing/providers/toast-provider.mock'; + +const DEFAULT_DRAFT = { + id: 'draft-1', + providerId: 'prov-1', + currentUserPermissions: [], + hasProject: false, + license: { options: {} }, + branchedFrom: { id: 'proj-1', type: 'nodes' }, +}; + +function createDefaultSignals(overrides: { selector: any; value: any }[] = []) { + const defaults = [ + { selector: RegistriesSelectors.getPagesSchema, value: [] }, + { selector: RegistriesSelectors.getDraftRegistration, value: DEFAULT_DRAFT }, + { selector: RegistriesSelectors.isDraftSubmitting, value: false }, + { selector: RegistriesSelectors.isDraftLoading, value: false }, + { selector: RegistriesSelectors.getStepsData, value: {} }, + { selector: RegistriesSelectors.getRegistrationComponents, value: [] }, + { selector: RegistriesSelectors.getRegistrationLicense, value: null }, + { selector: RegistriesSelectors.getRegistration, value: { id: 'new-reg-1' } }, + { selector: RegistriesSelectors.getStepsState, value: { 0: { invalid: false } } }, + { selector: RegistriesSelectors.hasDraftAdminAccess, value: true }, + { selector: ContributorsSelectors.getContributors, value: [] }, + { selector: ContributorsSelectors.isContributorsLoading, value: false }, + { selector: ContributorsSelectors.hasMoreContributors, value: false }, + { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, + ]; + + return overrides.length + ? defaults.map((s) => { + const override = overrides.find((o) => o.selector === s.selector); + return override ? { ...s, value: override.value } : s; + }) + : defaults; +} + +function setup( + opts: { + selectorOverrides?: { selector: any; value: any }[]; + dialogCloseSubject?: Subject; + } = {} +) { + const mockRouter = RouterMockBuilder.create().withUrl('/registries/123/review').build(); + const mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build(); + + const dialogClose$ = opts.dialogCloseSubject ?? new Subject(); + const mockDialog = CustomDialogServiceMockBuilder.create() + .withOpen( + jest.fn().mockReturnValue({ + onClose: dialogClose$.pipe(), + close: jest.fn(), + }) + ) + .build(); + + const mockToast = ToastServiceMock.simple(); + const mockConfirmation = CustomConfirmationServiceMock.simple(); + + TestBed.configureTestingModule({ + imports: [ + ReviewComponent, + ...MockComponents(RegistrationBlocksDataComponent, ContributorsListComponent, LicenseDisplayComponent), + ], + providers: [ + provideOSFCore(), + MockProvider(ActivatedRoute, mockActivatedRoute), + MockProvider(Router, mockRouter), + MockProvider(CustomDialogService, mockDialog), + MockProvider(CustomConfirmationService, mockConfirmation), + MockProvider(ToastService, mockToast), + provideMockStore({ signals: createDefaultSignals(opts.selectorOverrides) }), + ], + }); + + const store = TestBed.inject(Store); + const fixture = TestBed.createComponent(ReviewComponent); + const component = fixture.componentInstance; + fixture.detectChanges(); + + return { fixture, component, store, mockRouter, mockDialog, mockToast, mockConfirmation, dialogClose$ }; +} describe('ReviewComponent', () => { let component: ReviewComponent; - let fixture: ComponentFixture; - let mockRouter: ReturnType; - let mockActivatedRoute: ReturnType; - let mockDialog: ReturnType; - let mockConfirm: ReturnType; - let mockToast: ReturnType; - - beforeEach(async () => { - mockRouter = RouterMockBuilder.create().withUrl('/registries/123/review').build(); - mockActivatedRoute = ActivatedRouteMockBuilder.create().withParams({ id: 'draft-1' }).build(); - - mockDialog = CustomDialogServiceMockBuilder.create().withDefaultOpen().build(); - mockConfirm = CustomConfirmationServiceMockBuilder.create() - .withConfirmDelete(jest.fn((opts) => opts.onConfirm && opts.onConfirm())) - .build(); - mockToast = ToastServiceMockBuilder.create().build(); - - await TestBed.configureTestingModule({ - imports: [ - ReviewComponent, - OSFTestingModule, - ...MockComponents(RegistrationBlocksDataComponent, ContributorsListComponent, LicenseDisplayComponent), - ], - providers: [ - MockProvider(Router, mockRouter), - MockProvider(ActivatedRoute, mockActivatedRoute), - MockProvider(CustomDialogService, mockDialog), - MockProvider(CustomConfirmationService, mockConfirm), - MockProvider(ToastService, mockToast), - provideMockStore({ - signals: [ - { selector: RegistriesSelectors.getPagesSchema, value: [] }, - { - selector: RegistriesSelectors.getDraftRegistration, - value: { id: 'draft-1', providerId: 'prov-1', currentUserPermissions: [], hasProject: false }, - }, - { selector: RegistriesSelectors.isDraftSubmitting, value: false }, - { selector: RegistriesSelectors.isDraftLoading, value: false }, - { selector: RegistriesSelectors.getStepsData, value: {} }, - { selector: RegistriesSelectors.getRegistrationComponents, value: [] }, - { selector: RegistriesSelectors.getRegistrationLicense, value: null }, - { selector: RegistriesSelectors.getRegistration, value: { id: 'new-reg-1' } }, - { selector: RegistriesSelectors.getStepsState, value: { 0: { invalid: false } } }, - { selector: ContributorsSelectors.getContributors, value: [] }, - { selector: SubjectsSelectors.getSelectedSubjects, value: [] }, - ], - }), - ], - }).compileComponents(); + let store: Store; + let mockRouter: RouterMockType; + let mockDialog: CustomDialogServiceMockType; + let mockToast: ToastServiceMockType; + let mockConfirmation: CustomConfirmationServiceMockType; + let dialogClose$: Subject; - fixture = TestBed.createComponent(ReviewComponent); - component = fixture.componentInstance; - fixture.detectChanges(); + beforeEach(() => { + const result = setup(); + component = result.component; + store = result.store; + mockRouter = result.mockRouter; + mockDialog = result.mockDialog; + mockToast = result.mockToast; + mockConfirmation = result.mockConfirmation; + dialogClose$ = result.dialogClose$; }); it('should create', () => { expect(component).toBeTruthy(); - expect(component.FieldType).toBe(FieldType); }); - it('should navigate back to previous step', () => { - const navSpy = jest.spyOn(TestBed.inject(Router), 'navigate'); + it('should dispatch getContributors, getSubjects and fetchLicenses on init', () => { + expect(store.dispatch).toHaveBeenCalledWith(new GetAllContributors('draft-1', ResourceType.DraftRegistration)); + expect(store.dispatch).toHaveBeenCalledWith(new FetchSelectedSubjects('draft-1', ResourceType.DraftRegistration)); + expect(store.dispatch).toHaveBeenCalledWith(new FetchLicenses('prov-1')); + }); + + it('should navigate to previous step on goBack', () => { + const { component: c, mockRouter: router } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getPagesSchema, value: [{ id: '1' }, { id: '2' }] }], + }); + + c.goBack(); + + expect(router.navigate).toHaveBeenCalledWith( + ['../', 2], + expect.objectContaining({ relativeTo: expect.anything() }) + ); + }); + + it('should navigate to step 0 when pages is empty on goBack', () => { component.goBack(); - expect(navSpy).toHaveBeenCalledWith(['../', 0], { relativeTo: TestBed.inject(ActivatedRoute) }); + + expect(mockRouter.navigate).toHaveBeenCalledWith( + ['../', 0], + expect.objectContaining({ relativeTo: expect.anything() }) + ); }); - it('should open confirmation dialog when deleting draft and navigate on confirm', () => { - const navSpy = jest.spyOn(TestBed.inject(Router), 'navigateByUrl'); - (component as any).actions = { - ...component.actions, - deleteDraft: jest.fn().mockReturnValue(of({})), - clearState: jest.fn(), - }; + it('should dispatch deleteDraft and navigate on confirm', () => { + mockConfirmation.confirmDelete.mockImplementation(({ onConfirm }: any) => onConfirm()); + (store.dispatch as jest.Mock).mockClear(); component.deleteDraft(); - expect(mockConfirm.confirmDelete).toHaveBeenCalled(); - expect(navSpy).toHaveBeenCalledWith('/registries/prov-1/new'); + expect(store.dispatch).toHaveBeenCalledWith(new DeleteDraft('draft-1')); + expect(store.dispatch).toHaveBeenCalledWith(new ClearState()); + expect(mockRouter.navigateByUrl).toHaveBeenCalledWith('/registries/prov-1/new'); + }); + + it('should open select components dialog when components exist', () => { + const { component: c, mockDialog: dialog } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getRegistrationComponents, value: [{ id: 'comp-1' }] }], + }); + + c.confirmRegistration(); + + expect(dialog.open).toHaveBeenCalled(); + const firstCallArgs = (dialog.open as jest.Mock).mock.calls[0]; + expect(firstCallArgs[1].header).toBe('registries.review.selectComponents.title'); }); - it('should open select components dialog when components exist and chain to confirm', () => { - (component as any).components = () => ['c1', 'c2']; - (mockDialog.open as jest.Mock).mockReturnValueOnce({ onClose: of(['c1']) } as any); + it('should open confirm registration dialog when no components', () => { component.confirmRegistration(); expect(mockDialog.open).toHaveBeenCalled(); - expect((mockDialog.open as jest.Mock).mock.calls.length).toBeGreaterThan(1); + const firstCallArgs = (mockDialog.open as jest.Mock).mock.calls[0]; + expect(firstCallArgs[1].header).toBe('registries.review.confirmation.title'); + }); + + it('should show success toast and navigate on successful registration', () => { + component.openConfirmRegistrationDialog(); + dialogClose$.next(true); + + expect(mockToast.showSuccess).toHaveBeenCalledWith('registries.review.confirmation.successMessage'); + expect(mockRouter.navigate).toHaveBeenCalledWith(['/new-reg-1/overview']); + }); + + it('should reopen select components dialog when confirm dialog closed with falsy result and components exist', () => { + const { + component: c, + mockDialog: dialog, + dialogClose$: close$, + } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getRegistrationComponents, value: [{ id: 'comp-1' }] }], + }); + + c.openConfirmRegistrationDialog(['comp-1']); + close$.next(false); + + expect(dialog.open).toHaveBeenCalledTimes(2); + }); + + it('should not navigate when confirm dialog closed with falsy result and no components', () => { + component.openConfirmRegistrationDialog(); + dialogClose$.next(false); + + expect(mockRouter.navigate).not.toHaveBeenCalled(); + }); + + it('should pass selected components from select dialog to confirm dialog', () => { + const selectClose$ = new Subject(); + const confirmClose$ = new Subject(); + let callCount = 0; + + const { component: c, mockDialog: dialog } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getRegistrationComponents, value: [{ id: 'comp-1' }] }], + }); + + (dialog.open as jest.Mock).mockImplementation(() => { + callCount++; + const subj = callCount === 1 ? selectClose$ : confirmClose$; + return { onClose: subj.pipe(), close: jest.fn() }; + }); + + c.openSelectComponentsForRegistrationDialog(); + selectClose$.next(['comp-1']); + + expect(dialog.open).toHaveBeenCalledTimes(2); + const secondCallArgs = (dialog.open as jest.Mock).mock.calls[1]; + expect(secondCallArgs[1].data.components).toEqual(['comp-1']); + }); + + it('should not open confirm dialog when select components dialog returns falsy', () => { + const selectClose$ = new Subject(); + + const { component: c, mockDialog: dialog } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getRegistrationComponents, value: [{ id: 'comp-1' }] }], + }); + + (dialog.open as jest.Mock).mockReturnValue({ + onClose: selectClose$.pipe(), + close: jest.fn(), + }); + + c.openSelectComponentsForRegistrationDialog(); + selectClose$.next(null); + + expect(dialog.open).toHaveBeenCalledTimes(1); + }); + + it('should dispatch loadMoreContributors', () => { + (store.dispatch as jest.Mock).mockClear(); + component.loadMoreContributors(); + expect(store.dispatch).toHaveBeenCalledWith(new LoadMoreContributors('draft-1', ResourceType.DraftRegistration)); + }); + + it('should dispatch resetContributorsState on destroy', () => { + (store.dispatch as jest.Mock).mockClear(); + component.ngOnDestroy(); + expect(store.dispatch).toHaveBeenCalledWith(new ResetContributorsState()); + }); + + it('should compute isDraftInvalid as false when all steps are valid', () => { + expect(component.isDraftInvalid()).toBe(false); + }); + + it('should compute isDraftInvalid as true when any step is invalid', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getStepsState, value: { 0: { invalid: true } } }], + }); + expect(c.isDraftInvalid()).toBe(true); + }); + + it('should compute registerButtonDisabled as false when valid and has admin access', () => { + expect(component.registerButtonDisabled()).toBe(false); + }); + + it('should compute registerButtonDisabled as true when draft is loading', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.isDraftLoading, value: true }], + }); + expect(c.registerButtonDisabled()).toBe(true); + }); + + it('should compute registerButtonDisabled as true when draft is invalid', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getStepsState, value: { 0: { invalid: true } } }], + }); + expect(c.registerButtonDisabled()).toBe(true); + }); + + it('should compute registerButtonDisabled as true when no admin access', () => { + const { component: c } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.hasDraftAdminAccess, value: false }], + }); + expect(c.registerButtonDisabled()).toBe(true); + }); + + it('should compute licenseOptionsRecord from draft license options', () => { + const { component: c } = setup({ + selectorOverrides: [ + { + selector: RegistriesSelectors.getDraftRegistration, + value: { ...DEFAULT_DRAFT, license: { options: { year: '2026', copyright: 'Test' } } }, + }, + ], + }); + expect(c.licenseOptionsRecord()).toEqual({ year: '2026', copyright: 'Test' }); + }); + + it('should compute licenseOptionsRecord as empty when no license options', () => { + expect(component.licenseOptionsRecord()).toEqual({}); + }); + + it('should pass draftId and providerId to confirm registration dialog data', () => { + component.openConfirmRegistrationDialog(); + + const callArgs = (mockDialog.open as jest.Mock).mock.calls[0]; + expect(callArgs[1].data.draftId).toBe('draft-1'); + expect(callArgs[1].data.providerId).toBe('prov-1'); + expect(callArgs[1].data.projectId).toBe('proj-1'); + }); + + it('should set projectId to null when branchedFrom type is not nodes', () => { + const { component: c, mockDialog: dialog } = setup({ + selectorOverrides: [ + { + selector: RegistriesSelectors.getDraftRegistration, + value: { ...DEFAULT_DRAFT, branchedFrom: { id: 'proj-1', type: 'registrations' } }, + }, + ], + }); + + c.openConfirmRegistrationDialog(); + + const callArgs = (dialog.open as jest.Mock).mock.calls[0]; + expect(callArgs[1].data.projectId).toBeNull(); + }); + + it('should pass components array to confirm registration dialog', () => { + component.openConfirmRegistrationDialog(['comp-1', 'comp-2']); + + const callArgs = (mockDialog.open as jest.Mock).mock.calls[0]; + expect(callArgs[1].data.components).toEqual(['comp-1', 'comp-2']); + }); + + it('should not navigate after registration when newRegistration has no id', () => { + const { + component: c, + mockRouter: router, + mockToast: toast, + dialogClose$: close$, + } = setup({ + selectorOverrides: [{ selector: RegistriesSelectors.getRegistration, value: { id: null } }], + }); + + c.openConfirmRegistrationDialog(); + close$.next(true); + + expect(toast.showSuccess).toHaveBeenCalled(); + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('should dispatch getProjectsComponents when draft hasProject is true', () => { + const { store: s } = setup({ + selectorOverrides: [ + { + selector: RegistriesSelectors.getDraftRegistration, + value: { ...DEFAULT_DRAFT, hasProject: true }, + }, + ], + }); + + expect(s.dispatch).toHaveBeenCalledWith(new FetchProjectChildren('proj-1')); + }); + + it('should dispatch getProjectsComponents with empty string when branchedFrom has no id', () => { + const { store: s } = setup({ + selectorOverrides: [ + { + selector: RegistriesSelectors.getDraftRegistration, + value: { ...DEFAULT_DRAFT, hasProject: true, branchedFrom: null }, + }, + ], + }); + + expect(s.dispatch).toHaveBeenCalledWith(new FetchProjectChildren('')); + }); + + it('should not dispatch getProjectsComponents when isDraftSubmitting is true', () => { + const { store: s } = setup({ + selectorOverrides: [ + { selector: RegistriesSelectors.isDraftSubmitting, value: true }, + { + selector: RegistriesSelectors.getDraftRegistration, + value: { ...DEFAULT_DRAFT, hasProject: true }, + }, + ], + }); + + expect(s.dispatch).not.toHaveBeenCalledWith(expect.any(FetchProjectChildren)); }); }); diff --git a/src/app/features/registries/components/review/review.component.ts b/src/app/features/registries/components/review/review.component.ts index 0d9f2c339..bc634acbb 100644 --- a/src/app/features/registries/components/review/review.component.ts +++ b/src/app/features/registries/components/review/review.component.ts @@ -7,10 +7,19 @@ import { Card } from 'primeng/card'; import { Message } from 'primeng/message'; import { Tag } from 'primeng/tag'; -import { map, of } from 'rxjs'; +import { filter, map } from 'rxjs'; -import { ChangeDetectionStrategy, Component, computed, effect, inject, OnDestroy } from '@angular/core'; -import { toSignal } from '@angular/core/rxjs-interop'; +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + inject, + OnDestroy, + signal, +} from '@angular/core'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; import { ActivatedRoute, Router } from '@angular/router'; import { ENVIRONMENT } from '@core/provider/environment.provider'; @@ -18,10 +27,7 @@ import { ContributorsListComponent } from '@osf/shared/components/contributors-l import { LicenseDisplayComponent } from '@osf/shared/components/license-display/license-display.component'; import { RegistrationBlocksDataComponent } from '@osf/shared/components/registration-blocks-data/registration-blocks-data.component'; import { INPUT_VALIDATION_MESSAGES } from '@osf/shared/constants/input-validation-messages.const'; -import { FieldType } from '@osf/shared/enums/field-type.enum'; import { ResourceType } from '@osf/shared/enums/resource-type.enum'; -import { UserPermissions } from '@osf/shared/enums/user-permissions.enum'; -import { FixSpecialCharPipe } from '@osf/shared/pipes/fix-special-char.pipe'; 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'; @@ -33,14 +39,7 @@ import { } from '@osf/shared/stores/contributors'; import { FetchSelectedSubjects, SubjectsSelectors } from '@osf/shared/stores/subjects'; -import { - ClearState, - DeleteDraft, - FetchLicenses, - FetchProjectChildren, - RegistriesSelectors, - UpdateStepState, -} from '../../store'; +import { ClearState, DeleteDraft, FetchLicenses, FetchProjectChildren, RegistriesSelectors } from '../../store'; import { ConfirmRegistrationDialogComponent } from '../confirm-registration-dialog/confirm-registration-dialog.component'; import { SelectComponentsDialogComponent } from '../select-components-dialog/select-components-dialog.component'; @@ -55,7 +54,6 @@ import { SelectComponentsDialogComponent } from '../select-components-dialog/sel RegistrationBlocksDataComponent, ContributorsListComponent, LicenseDisplayComponent, - FixSpecialCharPipe, ], templateUrl: './review.component.html', styleUrl: './review.component.scss', @@ -67,6 +65,7 @@ export class ReviewComponent implements OnDestroy { private readonly customConfirmationService = inject(CustomConfirmationService); private readonly customDialogService = inject(CustomDialogService); private readonly toastService = inject(ToastService); + private readonly destroyRef = inject(DestroyRef); private readonly environment = inject(ENVIRONMENT); readonly pages = select(RegistriesSelectors.getPagesSchema); @@ -74,68 +73,65 @@ export class ReviewComponent implements OnDestroy { readonly isDraftSubmitting = select(RegistriesSelectors.isDraftSubmitting); readonly isDraftLoading = select(RegistriesSelectors.isDraftLoading); readonly stepsData = select(RegistriesSelectors.getStepsData); - readonly INPUT_VALIDATION_MESSAGES = INPUT_VALIDATION_MESSAGES; + readonly components = select(RegistriesSelectors.getRegistrationComponents); + readonly license = select(RegistriesSelectors.getRegistrationLicense); + readonly newRegistration = select(RegistriesSelectors.getRegistration); + readonly stepsState = select(RegistriesSelectors.getStepsState); readonly contributors = select(ContributorsSelectors.getContributors); readonly areContributorsLoading = select(ContributorsSelectors.isContributorsLoading); readonly hasMoreContributors = select(ContributorsSelectors.hasMoreContributors); readonly subjects = select(SubjectsSelectors.getSelectedSubjects); - readonly components = select(RegistriesSelectors.getRegistrationComponents); - readonly license = select(RegistriesSelectors.getRegistrationLicense); - readonly newRegistration = select(RegistriesSelectors.getRegistration); + readonly hasAdminAccess = select(RegistriesSelectors.hasDraftAdminAccess); - readonly FieldType = FieldType; - - actions = createDispatchMap({ + private readonly actions = createDispatchMap({ getContributors: GetAllContributors, getSubjects: FetchSelectedSubjects, deleteDraft: DeleteDraft, clearState: ClearState, getProjectsComponents: FetchProjectChildren, fetchLicenses: FetchLicenses, - updateStepState: UpdateStepState, loadMoreContributors: LoadMoreContributors, resetContributorsState: ResetContributorsState, }); - private readonly draftId = toSignal(this.route.params.pipe(map((params) => params['id'])) ?? of(undefined)); - - stepsState = select(RegistriesSelectors.getStepsState); - - isDraftInvalid = computed(() => Object.values(this.stepsState()).some((step) => step.invalid)); + readonly INPUT_VALIDATION_MESSAGES = INPUT_VALIDATION_MESSAGES; - licenseOptionsRecord = computed(() => (this.draftRegistration()?.license.options ?? {}) as Record); + private readonly draftId = toSignal(this.route.params.pipe(map((params) => params['id']))); - hasAdminAccess = computed(() => { - const registry = this.draftRegistration(); - if (!registry) return false; - return registry.currentUserPermissions.includes(UserPermissions.Admin); + private readonly resolvedProviderId = computed(() => { + const draft = this.draftRegistration(); + return draft ? (draft.providerId ?? this.environment.defaultProvider) : undefined; }); + private readonly componentsLoaded = signal(false); + + isDraftInvalid = computed(() => Object.values(this.stepsState()).some((step) => step.invalid)); + licenseOptionsRecord = computed(() => (this.draftRegistration()?.license.options ?? {}) as Record); registerButtonDisabled = computed(() => this.isDraftLoading() || this.isDraftInvalid() || !this.hasAdminAccess()); constructor() { if (!this.contributors()?.length) { this.actions.getContributors(this.draftId(), ResourceType.DraftRegistration); } + if (!this.subjects()?.length) { this.actions.getSubjects(this.draftId(), ResourceType.DraftRegistration); } effect(() => { - if (this.draftRegistration()) { - this.actions.fetchLicenses(this.draftRegistration()?.providerId ?? this.environment.defaultProvider); + const providerId = this.resolvedProviderId(); + + if (providerId) { + this.actions.fetchLicenses(providerId); } }); - let componentsLoaded = false; effect(() => { - if (!this.isDraftSubmitting()) { - const draftRegistrations = this.draftRegistration(); - if (draftRegistrations?.hasProject) { - if (!componentsLoaded) { - this.actions.getProjectsComponents(draftRegistrations?.branchedFrom?.id ?? ''); - componentsLoaded = true; - } + if (!this.isDraftSubmitting() && !this.componentsLoaded()) { + const draft = this.draftRegistration(); + if (draft?.hasProject) { + this.actions.getProjectsComponents(draft.branchedFrom?.id ?? ''); + this.componentsLoaded.set(true); } } }); @@ -156,12 +152,13 @@ export class ReviewComponent implements OnDestroy { messageKey: 'registries.confirmDeleteDraft', onConfirm: () => { const providerId = this.draftRegistration()?.providerId; - this.actions.deleteDraft(this.draftId()).subscribe({ - next: () => { + this.actions + .deleteDraft(this.draftId()) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(() => { this.actions.clearState(); this.router.navigateByUrl(`/registries/${providerId}/new`); - }, - }); + }); }, }); } @@ -184,11 +181,11 @@ export class ReviewComponent implements OnDestroy { components: this.components(), }, }) - .onClose.subscribe((selectedComponents) => { - if (selectedComponents) { - this.openConfirmRegistrationDialog(selectedComponents); - } - }); + .onClose.pipe( + filter((selectedComponents) => !!selectedComponents), + takeUntilDestroyed(this.destroyRef) + ) + .subscribe((selectedComponents) => this.openConfirmRegistrationDialog(selectedComponents)); } openConfirmRegistrationDialog(components?: string[]): void { @@ -206,14 +203,16 @@ export class ReviewComponent implements OnDestroy { components, }, }) - .onClose.subscribe((res) => { + .onClose.pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((res) => { if (res) { this.toastService.showSuccess('registries.review.confirmation.successMessage'); - this.router.navigate([`/${this.newRegistration()?.id}/overview`]); - } else { - if (this.components()?.length) { - this.openSelectComponentsForRegistrationDialog(); + const id = this.newRegistration()?.id; + if (id) { + this.router.navigate([`/${id}/overview`]); } + } else if (this.components()?.length) { + this.openSelectComponentsForRegistrationDialog(); } }); } diff --git a/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.html b/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.html index 334e43284..bd927b1c2 100644 --- a/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.html +++ b/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.html @@ -13,7 +13,7 @@ class="w-12rem btn-full-width" [label]="'common.buttons.back' | translate" severity="info" - (click)="dialogRef.close()" + (onClick)="dialogRef.close()" /> - +
diff --git a/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.spec.ts b/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.spec.ts index 69346c419..e698bf519 100644 --- a/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.spec.ts +++ b/src/app/features/registries/components/select-components-dialog/select-components-dialog.component.spec.ts @@ -1,37 +1,39 @@ import { MockProvider } from 'ng-mocks'; +import { TreeNode } from 'primeng/api'; import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog'; import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ProjectShortInfoModel } from '../../models/project-short-info.model'; + import { SelectComponentsDialogComponent } from './select-components-dialog.component'; -import { OSFTestingModule } from '@testing/osf.testing.module'; +import { provideDynamicDialogRefMock } from '@testing/mocks/dynamic-dialog-ref.mock'; +import { provideOSFCore } from '@testing/osf.testing.provider'; describe('SelectComponentsDialogComponent', () => { let component: SelectComponentsDialogComponent; let fixture: ComponentFixture; - let dialogRefMock: { close: jest.Mock }; - let dialogConfigMock: DynamicDialogConfig; + let dialogRef: DynamicDialogRef; - const parent = { id: 'p1', title: 'Parent Project' } as any; - const components = [ + const parent: ProjectShortInfoModel = { id: 'p1', title: 'Parent Project' }; + const components: ProjectShortInfoModel[] = [ { id: 'c1', title: 'Child 1', children: [{ id: 'c1a', title: 'Child 1A' }] }, { id: 'c2', title: 'Child 2' }, - ] as any; - - beforeEach(async () => { - dialogRefMock = { close: jest.fn() } as any; - dialogConfigMock = { data: { parent, components } } as any; + ]; - await TestBed.configureTestingModule({ - imports: [SelectComponentsDialogComponent, OSFTestingModule], + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [SelectComponentsDialogComponent], providers: [ - MockProvider(DynamicDialogRef, dialogRefMock as any), - MockProvider(DynamicDialogConfig, dialogConfigMock as any), + provideOSFCore(), + provideDynamicDialogRefMock(), + MockProvider(DynamicDialogConfig, { data: { parent, components } }), ], - }).compileComponents(); + }); + dialogRef = TestBed.inject(DynamicDialogRef); fixture = TestBed.createComponent(SelectComponentsDialogComponent); component = fixture.componentInstance; fixture.detectChanges(); @@ -43,17 +45,14 @@ describe('SelectComponentsDialogComponent', () => { const root = component.components[0]; expect(root.label).toBe('Parent Project'); expect(root.children?.length).toBe(2); - const selectedKeys = new Set(component.selectedComponents.map((n) => n.key)); - expect(selectedKeys.has('p1')).toBe(true); - expect(selectedKeys.has('c1')).toBe(true); - expect(selectedKeys.has('c1a')).toBe(true); - expect(selectedKeys.has('c2')).toBe(true); + const selectedKeys = new Set(component.selectedComponents.map((n: TreeNode) => n.key)); + expect(selectedKeys).toEqual(new Set(['p1', 'c1', 'c1a', 'c2'])); }); it('should close with unique selected component ids including parent on continue', () => { component.continue(); - expect(dialogRefMock.close).toHaveBeenCalledWith(expect.arrayContaining(['p1', 'c1', 'c1a', 'c2'])); - const passed = (dialogRefMock.close as jest.Mock).mock.calls[0][0] as string[]; + expect(dialogRef.close).toHaveBeenCalledWith(expect.arrayContaining(['p1', 'c1', 'c1a', 'c2'])); + const passed = (dialogRef.close as jest.Mock).mock.calls[0][0] as string[]; expect(new Set(passed).size).toBe(passed.length); }); }); diff --git a/src/app/features/registries/models/attached-file.model.ts b/src/app/features/registries/models/attached-file.model.ts new file mode 100644 index 000000000..458dac9cf --- /dev/null +++ b/src/app/features/registries/models/attached-file.model.ts @@ -0,0 +1,3 @@ +import { FileModel } from '@osf/shared/models/files/file.model'; + +export type AttachedFile = Partial; 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 c716f46fe..bd6fc8631 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,8 +1,9 @@ import { Store } from '@ngxs/store'; -import { MockComponent } from 'ng-mocks'; +import { MockComponent, MockProvider } from 'ng-mocks'; import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute, Router } from '@angular/router'; import { RegistriesSelectors, UpdateDraft } from '@osf/features/registries/store'; import { DraftRegistrationModel } from '@osf/shared/models/registration/draft-registration.model'; @@ -13,8 +14,8 @@ import { DraftRegistrationCustomStepComponent } from './draft-registration-custo 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 { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; const MOCK_DRAFT: Partial = { @@ -41,8 +42,8 @@ describe('DraftRegistrationCustomStepComponent', () => { imports: [DraftRegistrationCustomStepComponent, MockComponent(CustomStepComponent)], providers: [ provideOSFCore(), - provideActivatedRouteMock(mockRoute), - provideRouterMock(mockRouter), + MockProvider(ActivatedRoute, mockRoute), + MockProvider(Router, mockRouter), provideMockStore({ signals: [ { selector: RegistriesSelectors.getStepsData, value: stepsData }, 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 00b39b835..c69986e1e 100644 --- a/src/app/features/registries/pages/justification/justification.component.spec.ts +++ b/src/app/features/registries/pages/justification/justification.component.spec.ts @@ -1,15 +1,16 @@ import { Store } from '@ngxs/store'; -import { MockComponents } from 'ng-mocks'; +import { MockComponents, MockProvider } from 'ng-mocks'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { NavigationEnd } from '@angular/router'; +import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; import { StepperComponent } from '@osf/shared/components/stepper/stepper.component'; import { SubHeaderComponent } from '@osf/shared/components/sub-header/sub-header.component'; 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 { LoaderService } from '@osf/shared/services/loader.service'; import { ClearState, FetchSchemaBlocks, FetchSchemaResponse, RegistriesSelectors } from '../../store'; @@ -17,9 +18,9 @@ import { JustificationComponent } from './justification.component'; 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 { LoaderServiceMock } from '@testing/providers/loader-service.mock'; +import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { 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); @@ -68,9 +69,9 @@ describe('JustificationComponent', () => { imports: [JustificationComponent, ...MockComponents(StepperComponent, SubHeaderComponent)], providers: [ provideOSFCore(), - provideActivatedRouteMock(mockRoute), - provideRouterMock(mockRouter), - provideLoaderServiceMock(loaderService), + MockProvider(ActivatedRoute, mockRoute), + MockProvider(Router, mockRouter), + MockProvider(LoaderService, loaderService), provideMockStore({ signals: [ { selector: RegistriesSelectors.getSchemaResponse, value: schemaResponse }, 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 b5bf6b208..1d2557ed9 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 { Store } from '@ngxs/store'; -import { MockComponents } from 'ng-mocks'; +import { MockComponents, MockProvider } from 'ng-mocks'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; +import { ActivatedRoute, Router } from '@angular/router'; import { UserSelectors } from '@core/store/user'; import { RegistrationTab } from '@osf/features/registries/enums'; @@ -19,11 +19,12 @@ import { DeleteDraft, FetchDraftRegistrations, FetchSubmittedRegistrations } fro import { MyRegistrationsComponent } from './my-registrations.component'; -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 { provideOSFCore } from '@testing/osf.testing.provider'; +import { CustomConfirmationServiceMock } from '@testing/providers/custom-confirmation-provider.mock'; +import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; +import { ToastServiceMock } from '@testing/providers/toast-provider.mock'; describe('MyRegistrationsComponent', () => { let component: MyRegistrationsComponent; @@ -45,10 +46,10 @@ describe('MyRegistrationsComponent', () => { ], providers: [ provideOSFCore(), - provideRouterMock(mockRouter), - provideActivatedRouteMock(mockRoute), - MockCustomConfirmationServiceProvider, - provideOSFToast(), + MockProvider(Router, mockRouter), + MockProvider(ActivatedRoute, mockRoute), + MockProvider(CustomConfirmationService, CustomConfirmationServiceMock.simple()), + MockProvider(ToastService, ToastServiceMock.simple()), provideMockStore({ signals: [ { selector: RegistriesSelectors.getDraftRegistrations, value: [] }, 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 7520a2198..8d90557a1 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,9 +1,10 @@ import { Store } from '@ngxs/store'; -import { MockComponents } from 'ng-mocks'; +import { MockComponents, MockProvider } 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'; @@ -19,7 +20,7 @@ import { GetRegistries, RegistriesSelectors } from '../../store'; import { RegistriesLandingComponent } from './registries-landing.component'; import { provideOSFCore } from '@testing/osf.testing.provider'; -import { provideRouterMock, RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('RegistriesLandingComponent', () => { @@ -45,7 +46,7 @@ describe('RegistriesLandingComponent', () => { ], providers: [ provideOSFCore(), - provideRouterMock(mockRouter), + MockProvider(Router, mockRouter), { provide: PLATFORM_ID, useValue: 'browser' }, provideMockStore({ signals: [ 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 6f53ec22f..ea8d99376 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,9 +1,10 @@ import { Store } from '@ngxs/store'; -import { MockComponents } from 'ng-mocks'; +import { MockComponents, MockProvider } from 'ng-mocks'; import { PLATFORM_ID } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; import { ClearCurrentProvider } from '@core/store/provider'; import { GlobalSearchComponent } from '@osf/shared/components/global-search/global-search.component'; @@ -21,7 +22,7 @@ import { RegistryProviderHeroComponent } from '../../components/registry-provide import { RegistriesProviderSearchComponent } from './registries-provider-search.component'; import { provideOSFCore } from '@testing/osf.testing.provider'; -import { ActivatedRouteMockBuilder, provideActivatedRouteMock } from '@testing/providers/route-provider.mock'; +import { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; const MOCK_PROVIDER: RegistryProviderDetails = { @@ -51,7 +52,7 @@ describe('RegistriesProviderSearchComponent', () => { ], providers: [ provideOSFCore(), - provideActivatedRouteMock(mockRoute), + MockProvider(ActivatedRoute, mockRoute), { provide: PLATFORM_ID, useValue: platformId }, provideMockStore({ signals: [ 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 86b056485..6aa227fc6 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,8 +1,9 @@ import { Store } from '@ngxs/store'; -import { MockComponents } from 'ng-mocks'; +import { MockComponents, MockProvider } 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, UpdateSchemaResponse } from '../../store'; @@ -10,8 +11,8 @@ import { RegistriesSelectors, UpdateSchemaResponse } from '../../store'; import { RevisionsCustomStepComponent } from './revisions-custom-step.component'; 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 { ActivatedRouteMockBuilder } from '@testing/providers/route-provider.mock'; +import { RouterMockBuilder, RouterMockType } from '@testing/providers/router-provider.mock'; import { provideMockStore } from '@testing/providers/store-provider.mock'; describe('RevisionsCustomStepComponent', () => { @@ -28,8 +29,8 @@ describe('RevisionsCustomStepComponent', () => { imports: [RevisionsCustomStepComponent, MockComponents(CustomStepComponent)], providers: [ provideOSFCore(), - provideActivatedRouteMock(mockRoute), - provideRouterMock(mockRouter), + MockProvider(ActivatedRoute, mockRoute), + MockProvider(Router, mockRouter), provideMockStore({ signals: [ { diff --git a/src/assets/i18n/en.json b/src/assets/i18n/en.json index 01ef03921..b6f5f392a 100644 --- a/src/assets/i18n/en.json +++ b/src/assets/i18n/en.json @@ -1180,7 +1180,7 @@ "title": "Select Destination", "dialogTitle": "Move file", "dialogTitleMultiple": "Move files", - "message": "Are you sure you want to move {{dragNodeName}} to {{dropNodeName}} ?", + "message": "Are you sure you want to move {{dragNodeName}} to {{dropNodeName}}?", "multipleFiles": "{{count}} files", "storage": "OSF Storage", "pathError": "Path is not specified!", diff --git a/src/testing/mocks/data.mock.ts b/src/testing/mocks/data.mock.ts index 0d24b1261..f8503e40b 100644 --- a/src/testing/mocks/data.mock.ts +++ b/src/testing/mocks/data.mock.ts @@ -58,6 +58,7 @@ export const MOCK_USER: UserModel = { allowIndexing: true, canViewReviews: true, mergedBy: undefined, + external_identity: {}, }; export const MOCK_USER_RELATED_COUNTS: UserRelatedCounts = { diff --git a/src/testing/osf.testing.provider.ts b/src/testing/osf.testing.provider.ts index f3710e33a..5667c36a0 100644 --- a/src/testing/osf.testing.provider.ts +++ b/src/testing/osf.testing.provider.ts @@ -5,12 +5,8 @@ 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 [ @@ -24,25 +20,3 @@ export function provideOSFCore() { 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/component-provider.mock.ts b/src/testing/providers/component-provider.mock.ts index 92f036bf4..a63fe60ad 100644 --- a/src/testing/providers/component-provider.mock.ts +++ b/src/testing/providers/component-provider.mock.ts @@ -39,7 +39,6 @@ import { Component, EventEmitter, Input } from '@angular/core'; export function MockComponentWithSignal(selector: string, inputs: string[] = [], outputs: string[] = []): Type { @Component({ selector, - standalone: true, template: '', }) class MockComponent {