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

BHBC-964: File upload component + tests #203

Merged
merged 4 commits into from
Apr 7, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
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
38 changes: 15 additions & 23 deletions app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@
"leaflet-draw": "~1.0.0",
"leaflet.locatecontrol": "~0.72.0",
"lodash-es": "~4.17.21",
"material-ui-dropzone": "~3.5.0",
"moment": "~2.29.1",
"node-sass": "~4.14.1",
"qs": "~6.9.4",
"react": "~16.14.0",
"react-dom": "~16.14.0",
"react-dropzone": "~11.3.2",
"react-leaflet": "~3.1.0",
"react-number-format": "~4.5.2",
"react-router": "~5.1.2",
Expand Down
31 changes: 31 additions & 0 deletions app/src/components/attachments/DropZone.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { fireEvent, render, waitFor } from '@testing-library/react';
import React from 'react';
import DropZone from './DropZone';

const onFiles = jest.fn();

const renderContainer = () => {
return render(<DropZone projectId={1} onFiles={onFiles} />);
};

describe('DropZone', () => {
it('matches the snapshot', () => {
const { asFragment } = renderContainer();

expect(asFragment()).toMatchSnapshot();
});

it('calls the `onFiles` callback when files are selected', async () => {
const { getByTestId } = renderContainer();

const testFile = new File(['test png content'], 'testpng.txt', { type: 'text/plain' });

const dropZoneInput = getByTestId('drop-zone-input');

fireEvent.change(dropZoneInput, { target: { files: [testFile] } });

await waitFor(() => {
expect(onFiles).toHaveBeenCalledWith([testFile], [], expect.any(Object));
});
});
});
74 changes: 74 additions & 0 deletions app/src/components/attachments/DropZone.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { Box, Link, makeStyles, Typography } from '@material-ui/core';
import { mdiTrayPlus } from '@mdi/js';
import Icon from '@mdi/react';
import React from 'react';
import Dropzone from 'react-dropzone';

const useStyles = makeStyles(() => ({
browseLink: {
cursor: 'pointer'
}
}));

const MAX_FILES = Number(process.env.REACT_APP_MAX_FILES) || 10;
const MAX_FILE_SIZE_BYTES = Number(process.env.REACT_APP_MAX_FILE_SIZE) || 52428800;
const MAX_FILE_SIZE_MEGABYTES = Math.round(MAX_FILE_SIZE_BYTES / 1048576);

export interface IFileUploadProps {
/**
* Project ID.
*
* @type {number}
* @memberof IFileUploadProps
*/
projectId: number;
/**
* Function called when files are added (via either drag/drop or browsing).
*
* @memberof IFileUploadProps
*/
onFiles: (files: File[]) => void;
/**
* Maximum number of files allowed. Defaults to REACT_APP_MAX_FILES or 10.
*
* @type {number}
* @memberof IFileUploadProps
*/
maxFiles?: number;
/**
* Maximum file size allowed (in bytes). Defaults to REACT_APP_MAX_FILE_SIZE or 52428800 (50MB).
*
* @type {number}
* @memberof IFileUploadProps
*/
maxFileSize?: number;
}

export const DropZone: React.FC<IFileUploadProps> = (props) => {
const classes = useStyles();

return (
<Dropzone
maxFiles={props.maxFiles || MAX_FILES}
maxSize={props.maxFileSize || MAX_FILE_SIZE_BYTES}
onDrop={props.onFiles}>
{({ getRootProps, getInputProps }) => (
<section>
<Box {...getRootProps()}>
<input {...getInputProps()} data-testid="drop-zone-input" />
<Box m={3} display="flex" flexDirection="column" alignItems="center">
<Icon path={mdiTrayPlus} size={1} />
<Typography>
Drag your files here, or <Link className={classes.browseLink}>Browse Files</Link>
</Typography>
<Typography>{`Maximum file size: ${MAX_FILE_SIZE_MEGABYTES} MB`}</Typography>
<Typography>{`Maximum file count: ${MAX_FILES}`}</Typography>
</Box>
</Box>
</section>
)}
</Dropzone>
);
};

export default DropZone;
112 changes: 112 additions & 0 deletions app/src/components/attachments/FileUpload.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { fireEvent, render, waitFor } from '@testing-library/react';
import { APIError } from 'hooks/api/useAxios';
import { useBiohubApi } from 'hooks/useBioHubApi';
import React from 'react';
import FileUpload from './FileUpload';

jest.mock('../../hooks/useBioHubApi');
const mockUseBiohubApi = {
project: {
uploadProjectArtifacts: jest.fn<Promise<any>, []>()
}
};

const mockBiohubApi = ((useBiohubApi as unknown) as jest.Mock<typeof mockUseBiohubApi>).mockReturnValue(
mockUseBiohubApi
);

const projectId = 1;

const renderContainer = () => {
return render(<FileUpload projectId={projectId} />);
};

describe('FileUpload', () => {
it('matches the snapshot', () => {
NickPhura marked this conversation as resolved.
Show resolved Hide resolved
const { asFragment } = renderContainer();

expect(asFragment()).toMatchSnapshot();
});

it('handles file upload success', async () => {
let resolveRef: (value: unknown) => void;

const mockUploadPromise = new Promise(function (resolve: any, reject: any) {
resolveRef = resolve;
});

mockBiohubApi().project.uploadProjectArtifacts.mockReturnValue(mockUploadPromise);

const { asFragment, getByTestId, getByText } = renderContainer();

const testFile = new File(['test png content'], 'testpng.txt', { type: 'text/plain' });

const dropZoneInput = getByTestId('drop-zone-input');

fireEvent.change(dropZoneInput, { target: { files: [testFile] } });

await waitFor(() => {
expect(mockBiohubApi().project.uploadProjectArtifacts).toHaveBeenCalledWith(
projectId,
[testFile],
expect.any(Object),
expect.any(Function)
);

expect(getByText('testpng.txt')).toBeVisible();

expect(getByText('uploading')).toBeVisible();
});

// Manually trigger the upload resolve to simulate a successful upload
// @ts-ignore
resolveRef(null);

await waitFor(() => {
expect(getByText('complete')).toBeVisible();
});

expect(asFragment()).toMatchSnapshot();
});

it('handles file upload failure', async () => {
let rejectRef: (reason: unknown) => void;

const mockUploadPromise = new Promise(function (resolve: any, reject: any) {
rejectRef = reject;
});

mockBiohubApi().project.uploadProjectArtifacts.mockReturnValue(mockUploadPromise);

const { asFragment, getByTestId, getByText } = renderContainer();

const testFile = new File(['test png content'], 'testpng.txt', { type: 'text/plain' });

const dropZoneInput = getByTestId('drop-zone-input');

fireEvent.change(dropZoneInput, { target: { files: [testFile] } });

await waitFor(() => {
expect(mockBiohubApi().project.uploadProjectArtifacts).toHaveBeenCalledWith(
projectId,
[testFile],
expect.any(Object),
expect.any(Function)
);

expect(getByText('testpng.txt')).toBeVisible();

expect(getByText('uploading')).toBeVisible();
});

// Manually trigger the upload reject to simulate an unsuccessful upload
// @ts-ignore
rejectRef(new APIError({ response: { data: { message: 'File was evil!' } } } as any));

await waitFor(() => {
expect(getByText('File was evil!')).toBeVisible();
});

expect(asFragment()).toMatchSnapshot();
});
});
Loading