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

DSEGOG-364 delete an existing user #519

Draft
wants to merge 2 commits into
base: DSEGOG-363-edit-a-user
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
32 changes: 31 additions & 1 deletion cypress/e2e/users.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ describe('Users', () => {
});
});

describe('modify authorised routes ', () => {
describe('modify authorised routes', () => {
beforeEach(() => {
cy.visit('/admin/users');
cy.findAllByRole('button', { name: 'Row Actions' }).first().click();
Expand Down Expand Up @@ -212,4 +212,34 @@ describe('Users', () => {
);
});
});

describe('delete users', () => {
beforeEach(() => {
cy.visit('/admin/users');
cy.findAllByRole('button', { name: 'Row Actions' }).first().click();
cy.findByText('Delete').click();
});

afterEach(() => {
cy.clearMocks();
});

it('sends a delete request when an admin deletes a user', () => {
cy.findAllByTestId('delete-user-name').should('have.text', 'user1');

cy.startSnoopingBrowserMockedRequest();

cy.findByRole('button', { name: 'Continue' }).click();

cy.findBrowserMockedRequests({
method: 'DELETE',
url: '/users/:id',
}).should((deleteRequests) => {
expect(deleteRequests.length).equal(1);
const request = deleteRequests[0];

expect(request.url.toString()).to.contain('user1');
});
});
});
});
85 changes: 85 additions & 0 deletions src/admin/users/deleteUserDialogue.component.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { RenderResult, screen, waitFor } from '@testing-library/react';
import userEvent, { UserEvent } from '@testing-library/user-event';
import UsersJson from '../../mocks/users.json';
import { renderComponentWithProviders } from '../../testUtils';
import DeleteUserDialogue, {
DeleteUserDialogueProps,
} from './deleteUserDialogue.component';

describe('delete user dialogue', () => {
let props: DeleteUserDialogueProps;
let user: UserEvent;
const onClose = vi.fn();

const createView = (): RenderResult => {
return renderComponentWithProviders(<DeleteUserDialogue {...props} />);
};

beforeEach(() => {
props = {
open: true,
onClose: onClose,
selectedUser: UsersJson[0],
};
user = userEvent.setup();
});
afterEach(() => {
vi.clearAllMocks();
});
it('renders correctly', async () => {
createView();
expect(screen.getByText('Delete User')).toBeInTheDocument();
expect(screen.getByTestId('delete-user-name')).toHaveTextContent('user1');
});

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

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

it('displays warning message when user data is not loaded', async () => {
props = {
...props,
selectedUser: undefined,
};
createView();
const continueButton = screen.getByRole('button', { name: 'Continue' });
await user.click(continueButton);
const helperTexts = screen.getByText(
'No data provided, Please refresh and try again'
);
expect(helperTexts).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});

it('displays warning message when user data does not exist in database', async () => {
props = {
...props,
selectedUser: { ...UsersJson[0], _id: 'test' },
};
createView();

const continueButton = screen.getByRole('button', { name: 'Continue' });
await user.click(continueButton);
const helperTexts = await screen.findByText(
`username field must exist in the database. You put: 'test'`
);
expect(helperTexts).toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});

it('calls handleDeleteUser when continue button is clicked with a valid user name', async () => {
createView();
const continueButton = screen.getByRole('button', { name: 'Continue' });
await user.click(continueButton);

await waitFor(() => {
expect(onClose).toHaveBeenCalled();
});
});
});
67 changes: 67 additions & 0 deletions src/admin/users/deleteUserDialogue.component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormHelperText,
} from '@mui/material';
import { AxiosError } from 'axios';
import React from 'react';
import { useDeleteUser } from '../../api/user';
import { APIError, User } from '../../app.types';

export interface DeleteUserDialogueProps {
open: boolean;
onClose: () => void;
selectedUser?: User;
}

const DeleteUserDialogue = (props: DeleteUserDialogueProps) => {
const { open, onClose, selectedUser } = props;

const [errorMessage, setErrorMessage] = React.useState<string | undefined>(
undefined
);

const { mutateAsync: deleteUser } = useDeleteUser();

const handleClose = React.useCallback(() => {
onClose();
setErrorMessage(undefined);
}, [onClose]);

const handleDeleteUser = React.useCallback(() => {
if (selectedUser) {
deleteUser(selectedUser._id)
.then(() => {
handleClose();
})
.catch((error: AxiosError) => {
const errorDetail = (error.response?.data as APIError).detail;
setErrorMessage(errorDetail as string);
});
} else {
setErrorMessage('No data provided, Please refresh and try again');
}
}, [deleteUser, handleClose, selectedUser]);

return (
<Dialog open={open} onClose={handleClose} maxWidth="lg">
<DialogTitle>Delete User</DialogTitle>
<DialogContent>
Are you sure you want to delete{' '}
<strong data-testid="delete-user-name">{selectedUser?._id}</strong>?
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Close</Button>
<Button onClick={handleDeleteUser}>Continue</Button>
{errorMessage !== undefined && (
<FormHelperText error>{errorMessage}</FormHelperText>
)}
</DialogActions>
</Dialog>
);
};

export default DeleteUserDialogue;
27 changes: 27 additions & 0 deletions src/admin/users/usersTable.component.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,33 @@ describe('UsersTable Snapshot', () => {
});
});

it('opens delete dialog and closes it correctly', async () => {
createView();
await waitFor(() => {
expect(screen.getByText('user1')).toBeInTheDocument();
});

const addButtons = screen.getAllByRole('button', { name: 'Row Actions' });
await user.click(addButtons[0]);

await user.click(screen.getByText('Delete'));

await waitFor(() => {
expect(
screen.getByRole('dialog', { name: 'Delete User' })
).toBeInTheDocument();
});

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

await waitFor(() => {
expect(
screen.queryByRole('dialog', { name: 'Delete User' })
).not.toBeInTheDocument();
});
});

it('sets the table filters and clears the table filters', async () => {
createView();

Expand Down
32 changes: 30 additions & 2 deletions src/admin/users/usersTable.component.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import AddIcon from '@mui/icons-material/Add';
import ClearIcon from '@mui/icons-material/Clear';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import PasswordIcon from '@mui/icons-material/Password';
import {
Expand All @@ -20,6 +21,7 @@ import { MRT_Localization_EN } from 'material-react-table/locales/en';
import React from 'react';
import { useUsers } from '../../api/user';
import { User } from '../../app.types';
import DeleteUserDialogue from './deleteUserDialogue.component';
import UserDialogue from './userDialogue.component';

export const AUTHORISED_ROUTE_LIST = [
Expand All @@ -37,7 +39,7 @@ function UsersTable() {
const { data: userData, isLoading: userDataLoading } = useUsers();

const [requestType, setRequestType] = React.useState<
'patchPassword' | 'patchAuthorisedRoutes' | 'post'
'patchPassword' | 'patchAuthorisedRoutes' | 'post' | 'delete' | false
>('post');
const [selectedUser, setSelectedUser] = React.useState<User | undefined>(
undefined
Expand Down Expand Up @@ -194,10 +196,36 @@ function UsersTable() {
</MenuItem>,
]
: []),
<MenuItem
key="delete"
aria-label={`Delete user ${row.original._id}`}
onClick={() => {
setRequestType('delete');
setSelectedUser(row.original);
closeMenu();
}}
sx={{ m: 0 }}
>
<ListItemIcon>
<DeleteIcon />
</ListItemIcon>
<ListItemText>Delete</ListItemText>
</MenuItem>,
];
},
});
return <MaterialReactTable table={table} />;
return (
<>
<MaterialReactTable table={table} />
<DeleteUserDialogue
open={requestType === 'delete'}
onClose={() => {
setRequestType(false);
}}
selectedUser={selectedUser}
/>
</>
);
}

export default UsersTable;
23 changes: 22 additions & 1 deletion src/api/user.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { renderHook, waitFor } from '@testing-library/react';
import { User } from '../app.types';
import usersJson from '../mocks/users.json';
import { hooksWrapperWithProviders } from '../testUtils';
import { useAddUser, useEditUser, useUsers } from './user';
import { useAddUser, useDeleteUser, useEditUser, useUsers } from './user';

describe('useUsers', () => {
it('sends request to fetch users and returns successful response', async () => {
Expand Down Expand Up @@ -68,3 +68,24 @@ describe('useEditUser', () => {
'sends axios request to edit a user and throws an appropriate error on failure'
);
});

describe('useDeleteUser', () => {
it('delete request to delete user and returns successful response', async () => {
const { result } = renderHook(() => useDeleteUser(), {
wrapper: hooksWrapperWithProviders(),
});
expect(result.current.isIdle).toBe(true);

result.current.mutate('user1');

await waitFor(() => {
expect(result.current.isSuccess).toBeTruthy();
});

expect(result.current.data).toEqual('');
});

it.todo(
'sends axios request to delete user session and throws an appropriate error on failure'
);
});
28 changes: 28 additions & 0 deletions src/api/user.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,31 @@ export const useEditUser = (): UseMutationResult<
},
});
};

const deleteUser = (apiUrl: string, userId: string): Promise<void> => {
return axios
.delete(`${apiUrl}/users/${userId}`, {
headers: {
Authorization: `Bearer ${readSciGatewayToken()}`,
},
})
.then((response) => response.data);
};

export const useDeleteUser = (): UseMutationResult<
void,
AxiosError,
string
> => {
const { apiUrl } = useAppSelector(selectUrls);
const queryClient = useQueryClient();
return useMutation({
mutationFn: (userId: string) => deleteUser(apiUrl, userId),
onError: (error) => {
console.log('Got error ' + error.message);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['Users'] });
},
});
};
15 changes: 15 additions & 0 deletions src/mocks/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,4 +414,19 @@ export const handlers = [
const body = (await request.json()) as User;
return HttpResponse.json(body._id, { status: 201 });
}),

http.delete('/users/:id', async ({ params }) => {
const { id } = params;
const validId = usersJson.map((user) => user._id);
if (validId.includes(id as string)) {
return new HttpResponse(null, { status: 204 });
} else {
return HttpResponse.json(
{
detail: `username field must exist in the database. You put: '${id}'`,
},
{ status: 400 }
);
}
}),
];