Skip to content

Commit

Permalink
updating tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt Mangan committed Dec 12, 2023
1 parent f402382 commit 6a9cdce
Show file tree
Hide file tree
Showing 6 changed files with 143 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,19 @@ interface FormInputProps extends React.HTMLAttributes<FormInputElement> {
type?: 'text' | 'email' | 'password'
readOnly?: boolean
withinMultipleFieldsGroup?: boolean
name?: string
}

export function FormInput({
type = 'text',
name,
readOnly,
withinMultipleFieldsGroup,
...props
}: FormInputProps) {
return (
<FormElementLayout withinMultipleFieldsGroup={withinMultipleFieldsGroup}>
<FormBS.Control type={type} readOnly={readOnly} plaintext={readOnly} {...props} />
<FormBS.Control name={name} type={type} readOnly={readOnly} plaintext={readOnly} {...props} />
</FormElementLayout>
)
}
14 changes: 3 additions & 11 deletions src/Router.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { createBrowserRouter, RouterProvider, useRouteError } from 'react-router-dom'
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
import { HelloDataverse } from './sections/hello-dataverse/HelloDataverse'
import { Layout } from './sections/layout/Layout'
import { Route } from './sections/Route.enum'
import { DatasetFactory } from './sections/dataset/DatasetFactory'
import { PageNotFound } from './sections/page-not-found/PageNotFound'
import { CreateDataset } from './views/create-dataset/CreateDataset'
import CreateDatasetContainer from './views/create-dataset/CreateDatasetContainer'

const router = createBrowserRouter(
[
Expand All @@ -23,22 +23,14 @@ const router = createBrowserRouter(
},
{
path: `${Route.CREATE}`,
element: <CreateDataset />
element: <CreateDatasetContainer />
}
]
}
],
{ basename: import.meta.env.BASE_URL }
)

// Just a quick test for ensuring errorElements work correctly.
function ErrorBoundary() {
const error = useRouteError()
console.error(error)
// Uncaught ReferenceError: path is not defined
return <div>Dang!</div>
}

export function Router() {
return <RouterProvider router={router} />
}
80 changes: 34 additions & 46 deletions src/views/create-dataset/CreateDataset.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { ChangeEvent, FormEvent, useEffect, useState } from 'react'
// components/FormPresenter.tsx

import { ChangeEvent, FormEvent } from 'react'
import { Alert, Button, Col, Form, Row } from '@iqss/dataverse-design-system'
import { useTranslation } from 'react-i18next'
import { useDataset } from '../../sections/dataset/DatasetContext'
import { DatasetSkeleton } from '../../sections/dataset/DatasetSkeleton'
import { useLoading } from '../../sections/loading/LoadingContext'
// import { DatasetSkeleton } from '../../sections/dataset/DatasetSkeleton'
// import { useLoading } from '../../sections/loading/LoadingContext'
import styles from '/src/sections/dataset/Dataset.module.scss'
import { FormInputElement } from '@iqss/dataverse-design-system/src/lib/components/form/form-group/form-element/FormInput'
// import { FormInputElement } from '@iqss/dataverse-design-system/src/lib/components/form/form-group/form-element/FormInput'
import { SeparationLine } from '../../components/ui/SeparationLine/SeparationLine'
import { RequiredFieldText } from '../../components/Forms/RequiredFieldText/RequiredFieldText'

Expand All @@ -15,52 +16,34 @@ import { RequiredFieldText } from '../../components/Forms/RequiredFieldText/Requ
* Find submit action source
* cleanup state objects and submit process
* show submitted info in console
* Loading state management
*/

// See comments about https://rjsf-team.github.io/react-jsonschema-form/
// https://github.com/IQSS/dataverse-frontend/issues/231

export function CreateDataset() {
const { setIsLoading } = useLoading()
const { isLoading } = useDataset()
const { t } = useTranslation('createDataset')
const [submitting, setSubmitting] = useState(false)
const [submitStatus, setSubmitStatus] = useState(false)

useEffect(() => {
setIsLoading(isLoading)
}, [isLoading])

const [state, setState] = useState({
createDatasetTitle: ''
})

const handleCreateDatasetFieldChange = (e: ChangeEvent<FormInputElement>) => {
let value: (typeof state)[keyof typeof state] = e.target.value
if (e.target.type === 'text') {
value = e.target.value
}

setState({ ...state, [e.target.id]: value })
}

// TODO: Connect to API when ready
const handleCreateDatasetSubmit = (event: FormEvent<HTMLFormElement>) => {
setSubmitting(true)
event.preventDefault()
setTimeout(() => {
setSubmitting(false)
console.log('Form Submitted!')
setSubmitStatus(true)
}, 3000)
console.log(state)
// TODO: Callback for form submission should be here.
}
// const [submitting, setSubmitting] = useState(false)
// const [submitStatus, setSubmitStatus] = useState(false)

interface CreateDatasetFormPresenterProps {
formData: { createDatasetTitle: string }
handleCreateDatasetFieldChange: (event: ChangeEvent<HTMLInputElement>) => void
handleCreateDatasetSubmit: (event: FormEvent<HTMLFormElement>) => void
submitting: boolean
submitComplete: boolean
}
export default function CreateDatasetFormPresenter({
// formData,
handleCreateDatasetFieldChange,
handleCreateDatasetSubmit,
submitting,
submitComplete
}: CreateDatasetFormPresenterProps) {
const { t } = useTranslation('createDataset')
// TODO: Probably replace this with a FormSkeleton or remove entirely
if (isLoading) {
return <DatasetSkeleton />
}
// if (loading) {
// return <DatasetSkeleton />
// }
return (
<article>
<header className={styles.header}>
Expand All @@ -69,18 +52,21 @@ export function CreateDataset() {
<SeparationLine />
<div className={styles.container}>
<RequiredFieldText />
{submitting && <div>Submtting Form...</div>}
<Form onSubmit={handleCreateDatasetSubmit}>
{submitStatus && <div>Form Submitted!</div>}
{submitComplete && <div>Form Submitted!</div>}
<Row>
<Col md={9}>
<Form.Group controlId="createDatasetTitle" required>
<Form.Group.Label>{t('datasetForm.title')}</Form.Group.Label>
<Form.Group.Input
readOnly={submitting && true}
data-cy="datasetFormInputTitle"
type="text"
// FIX: Err - Property 'name' does not exist on type 'IntrinsicAttributes & FormInputProps'.
name="createDatasetTitle"
placeholder="Dataset Title"
onChange={handleCreateDatasetFieldChange}
withinMultipleFieldsGroup={false}
/>
</Form.Group>
</Col>
Expand Down Expand Up @@ -117,3 +103,5 @@ export function CreateDataset() {
</article>
)
}

// export default CreateDatasetFormPresenter
77 changes: 77 additions & 0 deletions src/views/create-dataset/CreateDatasetContainer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// containers/FormContainer.tsx

import React, { useState, ChangeEvent, FormEvent } from 'react'
import { FormInputElement } from '@iqss/dataverse-design-system/src/lib/components/form/form-group/form-element/FormInput'
import CreateDatasetUseCase from './CreateDatasetUseCase'
import CreateDatasetFormPresenter from './CreateDataset'

const CreateDatasetContainer: React.FC = () => {
const [formData, setFormData] = useState({
createDatasetTitle: ''
})

const [submitComplete, setSubmitComplete] = useState(false)

const [submitting, setSubmitting] = useState(false)

const handleCreateDatasetFieldChange = (event: ChangeEvent<FormInputElement>): void => {
const { name, value } = event.target
setFormData((prevData) => ({
...prevData,
[name]: value
}))
}

const handleCreateDatasetSubmit = async (event: FormEvent<HTMLFormElement>): Promise<void> => {
event.preventDefault()

const formUseCase = new CreateDatasetUseCase()

console.log('handleCreateDatasetSubmit() formData | ', formData)

if (formUseCase.validateCreateDatasetFormData(formData)) {
try {
setSubmitting(true)
console.log('Status: Submitting | ', submitting)

// Simulate an asynchronous operation, e.g., API call
await new Promise((resolve) => setTimeout(resolve, 3000))
const result = await formUseCase.submitCreateDatasetFormData(formData)
console.log(result)
setSubmitComplete(true)
// Handle success, e.g., show a success message
} catch (error) {
console.error('Error submitting form:', error)
// Handle error, e.g., show an error message
} finally {
setSubmitting(false)
}
} else {
// Handle validation error, e.g., show validation messages
console.error('Form validation failed')
}
// Explicitly return a Promise<void>
return Promise.resolve()
}

return (
// TODO: conditional view, needs to be lower in the component heirarchy
// {submitting && <div>Submtting Form...</div>}
<>
{submitting && <p>Submitting...</p>}
{!submitting && (
<CreateDatasetFormPresenter
submitComplete={submitComplete}
formData={formData}
handleCreateDatasetFieldChange={handleCreateDatasetFieldChange}
// TODO: Fix using IIFE (Immediately-invoked Function Expression)
// eslint-disable-next-line @typescript-eslint/no-misused-promises
handleCreateDatasetSubmit={handleCreateDatasetSubmit}
submitting={submitting}
/>
)}
</>
)
}

export default CreateDatasetContainer
23 changes: 23 additions & 0 deletions src/views/create-dataset/CreateDatasetUseCase.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// usecases/FormUseCase.js

'use strict'

interface CreateDatasetFormData {
createDatasetTitle: string
}

class CreateDatasetUseCase {
validateCreateDatasetFormData(formData: CreateDatasetFormData): boolean {
// Add your validation logic here
// For simplicity, assuming all fields are required
return formData.createDatasetTitle !== undefined && formData.createDatasetTitle.trim() !== ''
}

async submitCreateDatasetFormData(_formData: CreateDatasetFormData): Promise<string> {
// Add your business logic for form submission here
// For simplicity, returning a success message
return Promise.resolve('Form submitted successfully!')
}
}

export default CreateDatasetUseCase
6 changes: 3 additions & 3 deletions tests/component/views/create-dataset/CreateDataset.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { CreateDataset } from '../../../../src/views/create-dataset/CreateDataset'
import CreateDatasetContainer from '../../../../src/views/create-dataset/CreateDatasetContainer'

describe('Form component', () => {
it('should render all form fields', () => {
cy.customMount(<CreateDataset />)
cy.customMount(<CreateDatasetContainer />)
cy.get('[data-cy=datasetFormInputTitle]').should('be.visible')
cy.get('[data-cy=datasetFormSubmit]').should('be.visible')
cy.get('[data-cy=datasetFormCancel]').should('be.visible')
})

it('should submit the form with correct values', () => {
cy.customMount(<CreateDataset />)
cy.customMount(<CreateDatasetContainer />)

cy.get('[data-cy=datasetFormInputTitle]').type('Test Dataset Title')

Expand Down

0 comments on commit 6a9cdce

Please sign in to comment.