Skip to content

Commit

Permalink
Fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
eceeeren committed Nov 22, 2024
1 parent 815eb60 commit 0d228ea
Show file tree
Hide file tree
Showing 5 changed files with 279 additions and 72 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -219,12 +219,12 @@ else if (attachment.getExercise() != null) {
}

/**
* GET /attachments/:parentAttachmentId/hiddenAttachment : retrieve the hidden attachment associated with the given parent attachment ID.
* GET /attachments/:parentAttachmentId/hidden-attachment : retrieve the hidden attachment associated with the given parent attachment ID.
*
* @param parentAttachmentId the ID of the parent attachment for which to retrieve the hidden attachment
* @return the ResponseEntity with status 200 (OK) and the Attachment in the body, or a 404 (Not Found) if no matching attachment exists
*/
@GetMapping("attachments/{parentAttachmentId}/hiddenAttachment")
@GetMapping("attachments/{parentAttachmentId}/hidden-attachment")
@EnforceAtLeastTutor
public ResponseEntity<Attachment> getAttachmentByParentAttachmentId(@PathVariable Long parentAttachmentId) {
log.debug("REST request to get attachment by the parent attachment Id : {}", parentAttachmentId);
Expand Down
2 changes: 1 addition & 1 deletion src/main/webapp/app/lecture/attachment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export class AttachmentService {
*/
getAttachmentByParentAttachmentId(parentAttachmentId: number): Observable<EntityResponseType> {
return this.http
.get<Attachment>(`${this.resourceUrl}/${parentAttachmentId}/hiddenAttachment`, { observe: 'response' })
.get<Attachment>(`${this.resourceUrl}/${parentAttachmentId}/hidden-attachment`, { observe: 'response' })
.pipe(map((res: EntityResponseType) => this.convertAttachmentResponseDatesFromServer(res)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export class PdfPreviewComponent implements OnInit, OnDestroy {
private readonly attachmentService = inject(AttachmentService);
private readonly attachmentUnitService = inject(AttachmentUnitService);
private readonly lectureUnitService = inject(LectureUnitService);
private readonly alertService = inject(AlertService);
readonly alertService = inject(AlertService);
private readonly router = inject(Router);

dialogErrorSource = new Subject<string>();
Expand Down Expand Up @@ -301,7 +301,7 @@ export class PdfPreviewComponent implements OnInit, OnDestroy {
* Updates hidden pages after selected pages are deleted.
* @param pagesToDelete - Array of pages to be deleted (0-indexed).
*/
private updateHiddenPages(pagesToDelete: number[]) {
updateHiddenPages(pagesToDelete: number[]) {
const updatedHiddenPages = new Set<number>();
this.hiddenPages().forEach((hiddenPage) => {
// Adjust hiddenPage based on the deleted pages
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import { AlertService } from 'app/core/util/alert.service';
import { HttpClientModule } from '@angular/common/http';
import { TranslateService } from '@ngx-translate/core';
import { PdfPreviewThumbnailGridComponent } from 'app/lecture/pdf-preview/pdf-preview-thumbnail-grid/pdf-preview-thumbnail-grid.component';
import { getDocument } from 'pdfjs-dist';
import * as GlobalUtils from 'app/shared/util/global.utils';
import { ElementRef, Signal } from '@angular/core';

jest.mock('pdfjs-dist', () => {
return {
Expand Down Expand Up @@ -37,6 +40,7 @@ describe('PdfPreviewThumbnailGridComponent', () => {
beforeEach(async () => {
alertServiceMock = {
error: jest.fn(),
addAlert: jest.fn(),
};

await TestBed.configureTestingModule({
Expand All @@ -58,45 +62,130 @@ describe('PdfPreviewThumbnailGridComponent', () => {
jest.clearAllMocks();
});

it('should handle changes to inputs correctly in ngOnChanges', async () => {
const initialHiddenPages = new Set<number>([1, 2]);
const updatedHiddenPages = new Set<number>([3, 4]);
const initialPdfUrl = 'old-pdf-url';
const updatedPdfUrl = 'new-pdf-url';

fixture.componentRef.setInput('hiddenPages', initialHiddenPages);
fixture.componentRef.setInput('currentPdfUrl', initialPdfUrl);
fixture.detectChanges(); // Trigger initial bindings

const loadPdfSpy = jest.spyOn(component, 'loadPdf').mockImplementation();

fixture.componentRef.setInput('hiddenPages', updatedHiddenPages);
fixture.componentRef.setInput('currentPdfUrl', updatedPdfUrl);

component.ngOnChanges({
hiddenPages: {
previousValue: initialHiddenPages,
currentValue: updatedHiddenPages,
firstChange: false,
isFirstChange: () => false,
},
currentPdfUrl: {
previousValue: initialPdfUrl,
currentValue: updatedPdfUrl,
firstChange: false,
isFirstChange: () => false,
},
});

expect(component.newHiddenPages()).toEqual(updatedHiddenPages); // Check newHiddenPages signal is updated
expect(loadPdfSpy).toHaveBeenCalledWith(updatedPdfUrl, component.appendFile()); // Verify loadPdf is called with correct args
});

it('should load PDF and render pages', async () => {
const spyCreateCanvas = jest.spyOn(component, 'createCanvas');
const spyCreateCanvasContainer = jest.spyOn(component, 'createCanvasContainer');
fixture.componentRef.setInput('currentPdfUrl', 'fake-url');
fixture.componentRef.setInput('appendFile', false);

await component.loadOrAppendPdf('fake-url');
const mockCanvas = document.createElement('canvas');
jest.spyOn(component as any, 'createCanvas').mockReturnValue(mockCanvas);

expect(spyCreateCanvas).toHaveBeenCalled();
expect(spyCreateCanvasContainer).toHaveBeenCalled();
expect(component.totalPages()).toBe(1);
await component.loadPdf('fake-url', false);

expect(getDocument).toHaveBeenCalledWith('fake-url');
expect(component.totalPagesArray().size).toBe(1);
});

it('should toggle enlarged view state', () => {
const mockCanvas = document.createElement('canvas');
component.displayEnlargedCanvas(mockCanvas);
expect(component.isEnlargedView()).toBeTruthy();
it('should create and configure a canvas element for the given viewport', () => {
const mockViewport = {
width: 600,
height: 800,
};

const canvas = (component as any).createCanvas(mockViewport);

component.isEnlargedView.set(false);
expect(component.isEnlargedView()).toBeFalsy();
expect(canvas).toBeInstanceOf(HTMLCanvasElement);
expect(canvas.width).toBe(mockViewport.width);
expect(canvas.height).toBe(mockViewport.height);
expect(canvas.style.display).toBe('block');
expect(canvas.style.width).toBe('100%');
expect(canvas.style.height).toBe('100%');
});

it('should handle mouseenter and mouseleave events correctly', () => {
const mockCanvas = document.createElement('canvas');
const container = component.createCanvasContainer(mockCanvas, 1);
const overlay = container.querySelector('div');
it('should toggle visibility of a page correctly', () => {
const hiddenPagesMock = new Set<number>([1, 2]);
fixture.componentRef.setInput('hiddenPages', hiddenPagesMock);
component.toggleVisibility(2, new Event('click'));

expect(hiddenPagesMock.has(2)).toBeFalsy();
expect(hiddenPagesMock.has(1)).toBeTruthy();
});

container.dispatchEvent(new Event('mouseenter'));
expect(overlay!.style.opacity).toBe('1');
it('should toggle selection of a page correctly', () => {
const mockEvent = { target: { checked: true } } as unknown as Event;

container.dispatchEvent(new Event('mouseleave'));
expect(overlay!.style.opacity).toBe('0');
const initialSelectedPages = new Set<number>();
component.selectedPages.set(initialSelectedPages);
fixture.detectChanges();

component.togglePageSelection(1, mockEvent);

expect(component.selectedPages().has(1)).toBeTruthy();

(mockEvent.target as HTMLInputElement).checked = false;
component.togglePageSelection(1, mockEvent);

expect(component.selectedPages().has(1)).toBeFalsy();
});

it('should handle click event on overlay to trigger displayEnlargedCanvas', () => {
const displayEnlargedCanvasSpy = jest.spyOn(component, 'displayEnlargedCanvas');
const mockCanvas = document.createElement('canvas');
const container = component.createCanvasContainer(mockCanvas, 1);
const overlay = container.querySelector('div');
it('should handle PDF load errors gracefully', async () => {
const errorMessage = 'Error loading PDF';

(getDocument as jest.Mock).mockReturnValue({
promise: Promise.reject(new Error(errorMessage)),
});

overlay!.dispatchEvent(new Event('click'));
expect(displayEnlargedCanvasSpy).toHaveBeenCalledWith(mockCanvas);
const onErrorSpy = jest.spyOn(GlobalUtils, 'onError').mockImplementation();
await component.loadPdf('invalid-url', false);
expect(onErrorSpy).toHaveBeenCalledWith(alertServiceMock, new Error(errorMessage));
onErrorSpy.mockRestore();
});

it('should set the selected canvas as the originalCanvas and enable enlarged view', () => {
const mockCanvas = document.createElement('canvas');
const mockDiv = document.createElement('div');
mockDiv.id = 'pdf-page-1';
mockDiv.appendChild(mockCanvas);

const pdfContainerMock: ElementRef<HTMLDivElement> = {
nativeElement: {
querySelector: jest.fn((selector: string) => {
if (selector === '#pdf-page-1 canvas') {
return mockCanvas;
}
return null;
}),
},
} as unknown as ElementRef<HTMLDivElement>;

component.pdfContainer = jest.fn(() => pdfContainerMock) as unknown as Signal<ElementRef<HTMLDivElement>>;
component.displayEnlargedCanvas(1);

expect(pdfContainerMock.nativeElement.querySelector).toHaveBeenCalledWith('#pdf-page-1 canvas');
expect(component.originalCanvas()).toBe(mockCanvas);
expect(component.isEnlargedView()).toBeTrue();
});
});
Loading

0 comments on commit 0d228ea

Please sign in to comment.