Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Edit Dialog for Images #1151

Open
wants to merge 19 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
501 changes: 315 additions & 186 deletions cypress/e2e/with_mock_data/items.cy.ts

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions src/api/api.types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,12 @@ export interface ImagePost {
description?: string | null;
}

export interface ObjectFilePatch {
file_name?: string;
title?: string | null;
description?: string | null;
}

export interface APIImage
extends Required<Omit<ImagePost, 'upload_file'>>,
CreatedModifiedMixin {
Expand Down
33 changes: 31 additions & 2 deletions src/api/images.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@ import {
CREATED_MODIFIED_TIME_VALUES,
hooksWrapperWithProviders,
} from '../testUtils';
import { APIImage } from './api.types';
import { useDeleteImage, useGetImage, useGetImages } from './images';
import { APIImage, ObjectFilePatch } from './api.types';
import {
useDeleteImage,
useGetImage,
useGetImages,
usePatchImage,
} from './images';

describe('images api functions', () => {
afterEach(() => {
Expand Down Expand Up @@ -67,6 +72,30 @@ describe('images api functions', () => {
});
});

describe('usePatchImage', () => {
let mockDataPatch: ObjectFilePatch;
beforeEach(() => {
mockDataPatch = {
file_name: 'edited_image.jpeg',
title: 'an edited title',
description: 'an edited description',
};
});
it('sends a patch request to edit an image and returns a successful response', async () => {
const { result } = renderHook(() => usePatchImage(), {
wrapper: hooksWrapperWithProviders(),
});

result.current.mutate({ id: '1', fileMetadata: mockDataPatch });
await waitFor(() => expect(result.current.isSuccess).toBeTruthy());

expect(result.current.data).toEqual({
...ImagesJSON[0],
...mockDataPatch,
});
});
});

describe('useDeleteImage', () => {
let mockDataView: APIImage;
beforeEach(() => {
Expand Down
28 changes: 27 additions & 1 deletion src/api/images.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {

import { AxiosError } from 'axios';
import { storageApi } from './api';
import { APIImage, APIImageWithURL } from './api.types';
import { APIImage, APIImageWithURL, ObjectFilePatch } from './api.types';

export const getImage = async (id: string): Promise<APIImageWithURL> => {
return storageApi.get(`/images/${id}`).then((response) => {
Expand Down Expand Up @@ -51,6 +51,32 @@ export const useGetImages = (
});
};

const patchImage = async (
id: string,
fileMetadata: ObjectFilePatch
): Promise<APIImage> => {
return storageApi
.patch<APIImage>(`/images/${id}`, fileMetadata)
.then((response) => response.data);
};

export const usePatchImage = (): UseMutationResult<
APIImage,
AxiosError,
{ id: string; fileMetadata: ObjectFilePatch }
> => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, fileMetadata }) => patchImage(id, fileMetadata),
onSuccess: (updatedImage: APIImage) => {
queryClient.invalidateQueries({ queryKey: ['Images'] });
queryClient.invalidateQueries({
queryKey: ['Image', updatedImage.id],
});
},
});
};

const deleteImage = async (id: string): Promise<void> => {
return storageApi
.delete(`/images/${id}`, {})
Expand Down
158 changes: 158 additions & 0 deletions src/common/editFileDialog.component.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import { fireEvent, screen, waitFor } from '@testing-library/react';
import userEvent, { UserEvent } from '@testing-library/user-event';
import { http } from 'msw';
import { MockInstance } from 'vitest';
import { storageApi } from '../api/api';
import { usePatchImage } from '../api/images';
import handleIMS_APIError from '../handleIMS_APIError';
import ImagesJSON from '../mocks/Images.json';
import { server } from '../mocks/server';
import { renderComponentWithRouterProvider } from '../testUtils';
import EditFileDialog, { FileDialogProps } from './editFileDialog.component';

vi.mock('../handleIMS_APIError');

describe('Edit file dialog', () => {
const onClose = vi.fn();
let props: FileDialogProps;
let user: UserEvent;
const createView = () => {
return renderComponentWithRouterProvider(<EditFileDialog {...props} />);
};

beforeEach(() => {
props = {
open: true,
onClose: onClose,
fileType: 'Image',
usePatchFile: usePatchImage,
};
user = userEvent.setup();
});

afterEach(() => {
vi.clearAllMocks();
});
const modifyFileValues = (values: {
file_name?: string;
title?: string;
description?: string;
}) => {
if (values.file_name !== undefined)
fireEvent.change(screen.getByLabelText('File Name *'), {
target: { value: values.file_name },
});

if (values.title !== undefined)
fireEvent.change(screen.getByLabelText('Title'), {
target: { value: values.title },
});

if (values.description !== undefined)
fireEvent.change(screen.getByLabelText('Description'), {
target: { value: values.description },
});
};

describe('Edit an image', () => {
let axiosPatchSpy: MockInstance;
beforeEach(() => {
props = {
...props,
selectedFile: ImagesJSON[0],
};

axiosPatchSpy = vi.spyOn(storageApi, 'patch');
});

it('disables save button and shows circular progress indicator when request is pending', async () => {
server.use(
http.patch('/images/:id', () => {
return new Promise(() => {});
})
);

createView();

modifyFileValues({
file_name: 'Image A',
});

const saveButton = screen.getByRole('button', { name: 'Save' });
await user.click(saveButton);

expect(saveButton).toBeDisabled();
expect(await screen.findByRole('progressbar')).toBeInTheDocument();
});

it('Edits an image correctly', async () => {
createView();
modifyFileValues({
file_name: 'test_file_name.jpeg',
title: 'Test Title',
description: 'Test Description',
});

const saveButton = screen.getByRole('button', { name: 'Save' });

await user.click(saveButton);

expect(axiosPatchSpy).toHaveBeenCalledWith('/images/1', {
file_name: 'test_file_name.jpeg',
title: 'Test Title',
description: 'Test Description',
});

expect(onClose).toHaveBeenCalled();
});

it('No values changed shows correct error message', async () => {
asuresh-code marked this conversation as resolved.
Show resolved Hide resolved
createView();

const saveButton = screen.getByRole('button', { name: 'Save' });

await user.click(saveButton);

expect(
screen.getByText(
"There have been no changes made. Please change a field's value or press Cancel to exit."
)
).toBeInTheDocument();
});

it('Required fields show error if they are whitespace or current value just removed', async () => {
asuresh-code marked this conversation as resolved.
Show resolved Hide resolved
createView();
modifyFileValues({
file_name: '',
});
const saveButton = screen.getByRole('button', { name: 'Save' });

await user.click(saveButton);

expect(screen.getByText('Please enter a file name.')).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});

it('CatchAllError request works correctly and displays refresh page message', async () => {
asuresh-code marked this conversation as resolved.
Show resolved Hide resolved
createView();
modifyFileValues({
file_name: 'Error 500',
});
const saveButton = screen.getByRole('button', { name: 'Save' });

await user.click(saveButton);

expect(handleIMS_APIError).toHaveBeenCalled();
});

it('calls onClose when Close button is clicked', async () => {
createView();
const cancelButton = screen.getByRole('button', { name: 'Cancel' });
await user.click(cancelButton);

await waitFor(() => {
expect(onClose).toHaveBeenCalled();
});
});
});
});
Loading
Loading