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

feat: Add task request button to task details page #730

Merged
merged 7 commits into from
Aug 5, 2023
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
2 changes: 2 additions & 0 deletions __mocks__/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import issuesHandler from './handlers/issues.handler';
import standupHandler from './handlers/standup.handler';
import { prsHandler } from './handlers/pull-requests.handler';
import { progressHandler } from './handlers/progresses.handler';
import { taskRequestSuccessHandlers } from './handlers/task-request.handler';

const handlers = [
...mineTasksHandler,
Expand All @@ -28,6 +29,7 @@ const handlers = [
...issuesHandler,
...standupHandler,
...prsHandler,
...taskRequestSuccessHandlers
];

export default handlers;
18 changes: 18 additions & 0 deletions __mocks__/handlers/task-request.handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { rest } from 'msw';

const URL = process.env.NEXT_PUBLIC_BASE_URL;

export const taskRequestSuccessHandlers = [
rest.post(`${URL}/taskRequests/addOrUpdate`, (_, res, ctx) => {
return res(ctx.status(201), ctx.json({ message: 'Task request successfully created' }));
}),
];

export const taskRequestErrorHandler = [
rest.post(`${URL}/taskRequests/addOrUpdate`, (_, res, ctx) => {
return res(
ctx.status(409),
ctx.json({ message: 'taskId not provided' })
);
}),
];
83 changes: 83 additions & 0 deletions __tests__/Unit/Components/Tasks/TaskDetails.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { ButtonProps, TextAreaProps } from '@/interfaces/taskDetails.type';
import { ToastContainer } from 'react-toastify';
import * as progressQueries from '@/app/services/progressesApi';
import Details from '@/components/taskDetails/Details';
import { taskRequestErrorHandler } from '../../../../__mocks__/handlers/task-request.handler';
import { taskDetailsHandler } from '../../../../__mocks__/handlers/task-details.handler';

const details = {
url: 'https://realdevsquad.com/tasks/6KhcLU3yr45dzjQIVm0J/details',
Expand Down Expand Up @@ -247,6 +249,8 @@ describe('TaskDetails Page', () => {
});

test('should update the title and description with the new values', async () => {
server.use(...taskDetailsHandler);

renderWithRouter(
<Provider store={store()}>
<TaskDetails taskID={details.taskID} />
Expand Down Expand Up @@ -385,6 +389,85 @@ describe('Update Progress button', () => {
});
});

describe('Task Details > Task Request', () => {
it('should show task request button when dev is true', async () => {
renderWithRouter(
<Provider store={store()}>
<TaskDetails taskID={details.taskID} />
</Provider>,
{ query: { dev: 'true' } }
);

await waitFor(() => {
expect(
screen.queryByRole('button', { name: /request for task/i })
).not.toBeNull();
});
});

it('should not show task request button when dev is false', async () => {
renderWithRouter(
<Provider store={store()}>
<TaskDetails taskID={details.taskID} />
</Provider>
);

await waitFor(() => {
expect(
screen.queryByRole('button', { name: /request for task/i })
).toBeNull();
});
});

it('Success toast should be shown on success', async () => {
renderWithRouter(
<Provider store={store()}>
<TaskDetails taskID={details.taskID} />
<ToastContainer />
</Provider>,
{ query: { dev: 'true' } }
);
await waitFor(() => {
expect(
screen.queryByRole('button', { name: /request for task/i })
).not.toBeNull();
});

const taskRequestButton = screen.getByRole('button', {
name: /request for task/i,
});
fireEvent.click(taskRequestButton);

await waitFor(() => {
screen.getByText(/successfully requested for task/i);
});
});

it('Error toast should be shown on error', async () => {
server.use(...taskRequestErrorHandler);

renderWithRouter(
<Provider store={store()}>
<TaskDetails taskID={details.taskID} />
<ToastContainer />
</Provider>,
{ query: { dev: 'true' } }
);
await waitFor(() => {
screen.getByRole('button', { name: /request for task/i });
});

const taskRequestButton = screen.getByRole('button', {
name: /request for task/i,
});
fireEvent.click(taskRequestButton);

await waitFor(() => {
expect(screen.queryByText(/taskId not provided/i)).not.toBeNull();
});
});
});

describe('TaskDependency', () => {
it('should renders task titles', () => {
render(
Expand Down
76 changes: 76 additions & 0 deletions __tests__/Unit/hooks/taskRequestApi.tsx
Pratiyushkumar marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { store } from '@/app/store';
import { setupServer } from 'msw/node';
import { Provider } from 'react-redux';
import handlers from '../../../__mocks__/handlers';
import { PropsWithChildren } from 'react';
import { act, renderHook } from '@testing-library/react-hooks';
import { useAddOrUpdateMutation } from '@/app/services/taskRequestApi';
import { taskRequestErrorHandler } from '../../../__mocks__/handlers/task-request.handler';

function Wrapper({
children,
}: PropsWithChildren<Record<string, never>>): JSX.Element {
return <Provider store={store()}>{children}</Provider>;
}

const server = setupServer(...handlers);

describe('useAddOrUpdateMutation', () => {
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

it('should update the user', async () => {
const { result, waitForNextUpdate } = renderHook(
() => useAddOrUpdateMutation(),
{ wrapper: Wrapper }
);

const [addTask, initialResponse] = result.current;
expect(initialResponse.data).toBeUndefined();
expect(initialResponse.isLoading).toBe(false);

act(() => {
addTask({ taskId: 'taskId', userId: 'userId' });
});

expect(result.current[1].isLoading).toBe(true);

await act(() => waitForNextUpdate());

const response = result.current[1];
expect(response.data).not.toBeUndefined();
expect(response.data?.message).toBe(
'Task request successfully created'
);
expect(response.isLoading).toBe(false);
expect(response.isSuccess).toBe(true);
expect(response.isError).toBe(false);
});

it('should update the user', async () => {
server.use(...taskRequestErrorHandler);
const { result, waitForNextUpdate } = renderHook(
() => useAddOrUpdateMutation(),
{ wrapper: Wrapper }
);

const [addTask, initialResponse] = result.current;
expect(initialResponse.data).toBeUndefined();
expect(initialResponse.isLoading).toBe(false);

act(() => {
addTask({ taskId: 'taskId', userId: 'userId' });
});

expect(result.current[1].isLoading).toBe(true);

await act(() => waitForNextUpdate());

const response = result.current[1];
expect(response.error).not.toBeUndefined();
expect(response.isLoading).toBe(false);
expect(response.isSuccess).toBe(false);
expect(response.isError).toBe(true);
});
});
2 changes: 2 additions & 0 deletions src/app/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export const api = createApi({
'Challenges',
'Idle_Members',
'Progress_Details',
'User_Standup',
'TASK_REQUEST',
Pratiyushkumar marked this conversation as resolved.
Show resolved Hide resolved
],
/**
* This api has endpoints injected in adjacent files,
Expand Down
28 changes: 28 additions & 0 deletions src/app/services/taskRequestApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { api } from './api';

type AddOrUpdateMutationQuery = {
taskId: string;
userId: string;
};

type AddOrUpdateMutationQueryRes =
| { message: string }
| { message: string; requestors: string[] };

export const taskRequestApi = api.injectEndpoints({
endpoints: (build) => ({
addOrUpdate: build.mutation<
AddOrUpdateMutationQueryRes,
AddOrUpdateMutationQuery
>({
query: (body) => ({
url: 'taskRequests/addOrUpdate',
method: 'POST',
body,
}),
invalidatesTags: ['TASK_REQUEST'],
}),
}),
});

export const { useAddOrUpdateMutation } = taskRequestApi;
24 changes: 23 additions & 1 deletion src/components/taskDetails/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import TaskDependency from '@/components/taskDetails/taskDependency';
import { useGetProgressDetailsQuery } from '@/app/services/progressesApi';
import { ProgressDetailsData } from '@/types/standup.type';
import { getDateFromTimestamp } from '@/utils/getDateFromTimestamp';
import { useAddOrUpdateMutation } from '@/app/services/taskRequestApi';

export function Button(props: ButtonProps) {
const { buttonName, clickHandler, value } = props;
Expand Down Expand Up @@ -63,7 +64,7 @@ const TaskDetails: FC<Props> = ({ taskID }) => {
const { query } = router;
const isDevModeEnabled = query.dev === 'true' ? true : false;

const { isUserAuthorized } = useUserData();
const { isUserAuthorized, data: userData } = useUserData();

const [isEditing, setIsEditing] = useState<boolean>(false);
const { data, isError, isLoading, isFetching } =
Expand All @@ -80,6 +81,9 @@ const TaskDetails: FC<Props> = ({ taskID }) => {
taskDetailsDataType['taskData'] | undefined
>(data?.taskData);

const [addOrUpdateTaskRequest, taskRequestUpdateStatus] =
useAddOrUpdateMutation();

useEffect(() => {
if (data?.taskData) {
setEditedTaskDetails(data.taskData);
Expand Down Expand Up @@ -116,6 +120,16 @@ const TaskDetails: FC<Props> = ({ taskID }) => {
}));
}

function taskRequestHandle() {
if (!userData) {
return;
}
addOrUpdateTaskRequest({ taskId: taskID, userId: userData.id })
.unwrap()
.then(() => toast(SUCCESS, 'Successfully requested for task'))
.catch((error) => toast(ERROR, error.data.message));
}

function renderLoadingComponent() {
if (isLoading) {
return <p className={classNames.textCenter}>Loading...</p>;
Expand Down Expand Up @@ -317,6 +331,14 @@ const TaskDetails: FC<Props> = ({ taskID }) => {
)}
/>
</TaskContainer>
<TaskContainer
hasImg={false}
title="Request for task"
>
<button onClick={taskRequestHandle}>
Request for task
sahsisunny marked this conversation as resolved.
Show resolved Hide resolved
</button>
</TaskContainer>
</section>
</section>
</div>
Expand Down
Loading