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

Test create project #62

Merged
merged 9 commits into from
May 1, 2023
Merged
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
1 change: 1 addition & 0 deletions client/assets/css/__mocks__/styleMock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = {};
5 changes: 4 additions & 1 deletion client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@
"jest": {
"transformIgnorePatterns": [
"/node_modules/(?!(axios)/)"
]
],
"moduleNameMapper": {
"\\.(css|less)$": "<rootDir>/assets/css/__mocks__/styleMock.js"
}
}
}
74 changes: 74 additions & 0 deletions client/src/components/CreateProject.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import React from 'react';
import { render, fireEvent, screen, getByLabelText } from '../utils/test-utils';
import CreateProject from './CreateProject';
import { BrowserRouter } from 'react-router-dom';

describe('CreateProject rendering tests', () => {
const onClose = jest.fn();

it('renders the submit form', () => {
render(
<BrowserRouter>
<CreateProject open={true} onClose={onClose} />
</BrowserRouter>
);
const titleInput = screen.getByLabelText('Title:');
const descriptionInput = screen.getByText('Description:');
const imgInput = screen.getByLabelText('Image:');
const tagsInput = screen.getByLabelText('Tags:');
const submitBtn = screen.getByRole('submit-button');
const closeBtn = screen.getByRole('close-button');
expect(titleInput).toBeInTheDocument();
expect(descriptionInput).toBeInTheDocument();
expect(imgInput).toBeInTheDocument();
expect(tagsInput).toBeInTheDocument();
expect(submitBtn).toBeInTheDocument();
expect(closeBtn).toBeInTheDocument();
})

it('executes onClose() when closeBtn is clicked', () => {
render(
<BrowserRouter>
<CreateProject open={true} onClose={onClose} />
</BrowserRouter>
);
const closeBtn = screen.getByRole('close-button');
fireEvent.click(closeBtn)
expect(onClose).toHaveBeenCalled();
})

it('Does not render the component if open is false', () => {
render(
<BrowserRouter>
<CreateProject open={false} onClose={onClose} />
</BrowserRouter>
);
expect(document.querySelector('.overlay')).not.toBeInTheDocument();
})


it('Requires title and img inputs to be filled in order to submit the form', () => {
render(
<BrowserRouter>
<CreateProject open={true} onClose={onClose} />
</BrowserRouter>
);
const titleInput = screen.getByLabelText('Title:');
const imgInput = screen.getByLabelText('Image:');
const submitButton = screen.getByRole('submit-button');
expect(submitButton).toBeDisabled();

fireEvent.change(titleInput, { target: { value: 'Not empty' } });
expect(submitButton).toBeDisabled();

render(
<BrowserRouter>
<CreateProject open={true} onClose={onClose} />
</BrowserRouter>
);
fireEvent.change(imgInput, { target: { files: ['file'] } });
fireEvent.change(titleInput, { target: { value: 'Not empty' } });
expect(submitButton).not.toBeDisabled();
})
})

73 changes: 41 additions & 32 deletions client/src/components/CreateProject.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import React, { useState, useContext, Requireable } from 'react'
import '../styles/createProject.css'
import UserContext from '../context/UserContext'
import { UserContextType } from '../types/user.type'
import Axios from 'axios'
import { AxiosResponse } from 'axios'
import { useNavigate } from 'react-router-dom'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import Project from '../types/project.type'
import http from '../services/api.service'
import React, { useState, useContext, Requireable } from 'react';
import '../styles/createProject.css';
import UserContext from '../context/UserContext';
import { UserContextType } from '../types/user.type';
import Axios from 'axios';
import { useNavigate } from 'react-router-dom';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import Project from '../types/project.type';
import http from '../services/api.service';

const initialState: Project = {
title: '',
Expand All @@ -21,32 +20,35 @@ const initialState: Project = {
createdBy: null,
tags: [],
followers: [],
quillValue: ''
}
};

interface CreateProjectProps {
open: boolean | Requireable<boolean>
onClose: () => void
}

const CreateProject: React.FC<CreateProjectProps> = ({ open, onClose }) => {
if (!open) return null
const navigate = useNavigate()
const [selectedFile, setSelectedFile] = useState<File>() // We might not need an initial state here
const { user } = useContext<UserContextType>(UserContext)
const [projectInfo, setProjectInfo] = useState<Project>(initialState)
const [quillValue, setQuillValue] = useState<string>('')
if (!open) return null;
const navigate = useNavigate();
const [selectedFile, setSelectedFile] = useState<File>(); // We might not need an initial state here
const { user } = useContext<UserContextType>(UserContext);
const [projectInfo, setProjectInfo] = useState<Project>(initialState);
const [quillValue, setQuillValue] = useState<string>('');
const [submitDisabled, setSubmitDisabled] = useState<boolean>(true);

function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const { name, value } = e.target
setProjectInfo((prev) => ({
...prev,
[name]: value
}))
[name]: value,
}));
projectInfo.image ? setSubmitDisabled(false) : setSubmitDisabled(true);

}

function handleFileInputChange(e: React.ChangeEvent<HTMLInputElement>) {
if (e.target.files) setSelectedFile(e.target.files[0])
if (e.target.files) setSelectedFile(e.target.files[0]);
projectInfo.title ? setSubmitDisabled(false) : setSubmitDisabled(true);
}

async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
Expand All @@ -67,22 +69,25 @@ const CreateProject: React.FC<CreateProjectProps> = ({ open, onClose }) => {
console.log(error)
}

const project: Project = initialState
project.date = new Date().toLocaleDateString()
project.author = `${user?.firstName} ${user?.lastName}`
project.title = projectInfo.title
project.tags = projectInfo.tags
project.quillValue = quillValue
project.image = image
project.createdBy = user
const project: Project = initialState;
project.date = new Date().toLocaleDateString();
project.author = `${user?.firstName} ${user?.lastName}`;
project.title = projectInfo.title;
project.tags = projectInfo.tags;
project.description = quillValue;
project.image = image;
project.createdBy = user;


const response = await http.createProject(project) //project should be stringified, review api.service
if (response!.status > 400) {
alert('Error creating Project')
return
} else {
navigate(`/posts/${project.id}`)
onClose()
navigate(`/posts/${project.id}`);
onClose();
setSubmitDisabled(true);

}
}

Expand All @@ -93,13 +98,15 @@ const CreateProject: React.FC<CreateProjectProps> = ({ open, onClose }) => {
<button
onClick={onClose}
className='closeButton'
role='close-button'
>
X
</button>
<h1>Your new project</h1>
<form
onSubmit={handleSubmit}
className='postForm'
role='project-form'
>
<label htmlFor='title'>Title:</label>
<input
Expand Down Expand Up @@ -146,7 +153,9 @@ const CreateProject: React.FC<CreateProjectProps> = ({ open, onClose }) => {

<button
type='submit'
disabled={submitDisabled}
className='createNewProjectButton'
role='submit-button'
>
Create new project
</button>
Expand Down
87 changes: 87 additions & 0 deletions client/src/components/Login.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import React from 'react';
import { useContext, useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import UserContext from '../context/UserContext';
import '../styles/login.css';
import http from '../services/api.service';
import { useForm, SubmitHandler } from 'react-hook-form';

interface ICredentials {
email: string;
password: string;
}

const initialCredentials: ICredentials = {
email: '',
password: '',
};

interface IFormInput {
email: string;
password: string;
}

function Login() {
const { user, setUser } = useContext(UserContext);
const [credentials, setCredentials] = useState(initialCredentials);
const navigate = useNavigate();
const {
register,
handleSubmit,
formState: { errors },
} = useForm<IFormInput>();

const onSubmit: SubmitHandler<IFormInput> = async (data) => {
const response = await http.login(credentials);
if (response!.status === 401) {
alert('Wrong email or password');
return;
} else {
setUser(response!.data);
navigate('/home');
}
};

return (
<div className='loginContainer'>
<div className='anotherContainer'>
<h1>Login</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<label htmlFor='email'>email</label>
<input
id='email'
{...register('email', {
required: 'required',
pattern: {
value: /\S+@\S+\.\S+/,
message: 'Entered value does not match email format',
},
})}
type='email'
/>
{errors.email && <span role='alert'>{errors.email.message}</span>}
<label htmlFor='password'>password</label>
<input
id='password'
{...register('password', {
required: 'required',
minLength: {
value: 5,
message: 'min length is 5',
},
})}
type='password'
/>
{errors.password && (
<span role='alert'>{errors.password.message}</span>
)}
<button type='submit'>SUBMIT</button>
</form>
<span>Dont have an account?</span>
<Link to={'/register'}> Sign Up</Link>
</div>
</div>
);
}

export default Login;
3 changes: 1 addition & 2 deletions client/src/types/project.type.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ export default interface Project {
createdBy?: User | null;
date: string;
chat: string[];
tags: string[];
tags: string[] | string;
followers: User[] | string[] | [];
quillValue?: string,
}