Skip to content

Commit

Permalink
test: update form and update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
RitaDias committed Jul 15, 2024
1 parent 5cd0019 commit 208dffc
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 96 deletions.
108 changes: 38 additions & 70 deletions packages/sanity/src/core/bundles/components/dialog/BundleForm.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable i18next/no-literal-string */
import {CalendarIcon} from '@sanity/icons'
import {Box, Button, Flex, Popover, Stack, Text, TextArea, TextInput} from '@sanity/ui'
import {useCallback, useEffect, useMemo, useState} from 'react'
import {useCallback, useMemo, useState} from 'react'
import {
FormFieldHeaderText,
type FormNodeValidation,
Expand Down Expand Up @@ -39,60 +39,6 @@ export function BundleForm(props: {
const [titleErrors, setTitleErrors] = useState<FormNodeValidation[]>([])
const [dateErrors, setDateErrors] = useState<FormNodeValidation[]>([])

useEffect(() => {
const newTitleErrors: FormNodeValidation[] = []
const newDateErrors: FormNodeValidation[] = []

// if the title is 'drafts' or 'published', show an error
// TODO localize text
if (showIsDraftPublishError) {
newTitleErrors.push({
level: 'error',
message: "Title cannot be 'drafts' or 'published'",
path: [],
})
}

// if the bundle already exists, show an error
// TODO localize text
if (showBundleExists) {
newTitleErrors.push({
level: 'error',
message: 'Bundle already exists',
path: [],
})
}

// if the title is empty (but on not first render), show an error
// TODO localize text
if (!isInitialRender && title?.length === 0) {
newTitleErrors.push({
level: 'error',
message: 'Bundle needs a name',
path: [],
})
}

// if the date is invalid, show an error
// TODO localize text
if (showDateValidation) {
newDateErrors.push({
level: 'error',
message: 'Should be an empty or valid date',
path: [],
})
}

setTitleErrors(newTitleErrors)
setDateErrors(newDateErrors)
}, [
isInitialRender,
showBundleExists,
showDateValidation,
showIsDraftPublishError,
title?.length,
])

const publishAtDisplayValue = useMemo(() => {
if (!publishAt) return ''
return dateFormatter.format(new Date(publishAt as Date))
Expand All @@ -115,30 +61,42 @@ export function BundleForm(props: {
const pickedTitle = event.target.value
const pickedNameExists =
data && data.find((bundle) => bundle.name === speakingurl(pickedTitle))

if (isDraftOrPublished(pickedTitle) || pickedNameExists) {
const isEmptyTitle = pickedTitle.trim() === '' && !isInitialRender

if (
isDraftOrPublished(pickedTitle) ||
pickedNameExists ||
(isEmptyTitle && !isInitialRender)
) {
if (isEmptyTitle && !isInitialRender) {
// if the title is empty and it's not the first opening of the dialog, show an error
// TODO localize text

setTitleErrors([{level: 'error', message: 'Bundle needs a name', path: []}])
}
if (isDraftOrPublished(pickedTitle)) {
setShowIsDraftPublishError(true)
} else {
setShowIsDraftPublishError(false)
// if the title is 'drafts' or 'published', show an error
// TODO localize text
setTitleErrors([
{level: 'error', message: "Title cannot be 'drafts' or 'published'", path: []},
])
}

if (pickedNameExists) {
setShowBundleExists(true)
} else {
setShowBundleExists(false)
// if the bundle already exists, show an error
// TODO localize text
setTitleErrors([{level: 'error', message: 'Bundle already exists', path: []}])
}

onError(true)
} else {
setShowIsDraftPublishError(false)
setShowBundleExists(false)
setTitleErrors([])
onError(false)
}

setIsInitialRender(false)
onChange({...value, title: pickedTitle, name: speakingurl(pickedTitle)})
},
[data, onChange, onError, value],
[data, isInitialRender, onChange, onError, value],
)

const handleBundleDescriptionChange = useCallback(
Expand Down Expand Up @@ -172,15 +130,25 @@ export function BundleForm(props: {
// needs to check that the date is not invalid & not empty
// in which case it can update the input value but not the actual bundle value
if (new Date(event.target.value).toString() === 'Invalid Date' && dateValue !== '') {
setShowDateValidation(true)
// if the date is invalid, show an error
// TODO localize text
setDateErrors([
{
level: 'error',
message: 'Should be an empty or valid date',
path: [],
},
])
setDisplayDate(dateValue)
onError(true)
} else {
setShowDateValidation(false)
setDateErrors([])
setDisplayDate(dateValue)
onChange({...value, publishAt: dateValue})
onError(false)
}
},
[onChange, value],
[onChange, value, onError],
)

const handleIconValueChange = useCallback(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,24 @@ describe('BundleForm', () => {
onChangeMock.mockClear()
onErrorMock.mockClear()

mockUseBundleStore.mockReturnValue({
data: [],
loading: true,
dispatch: jest.fn(),
})
// Mock the data returned by useBundles hook
const mockData: BundleDocument[] = [
{
description: 'What a spring drop, allergies galore 🌸',
_updatedAt: '2024-07-12T10:39:32Z',
_rev: 'HdJONGqRccLIid3oECLjYZ',
authorId: 'pzAhBTkNX',
title: 'Spring Drop',
icon: 'heart-filled',
_id: 'db76c50e-358b-445c-a57c-8344c588a5d5',
_type: 'bundle',
name: 'spring-drop',
hue: 'magenta',
_createdAt: '2024-07-02T11:37:51Z',
},
// Add more mock data if needed
]
mockUseBundleStore.mockReturnValue({data: mockData, loading: false, dispatch: jest.fn()})

mockUseDateTimeFormat.mockReturnValue({format: jest.fn().mockReturnValue('Mocked date')})

Expand Down Expand Up @@ -96,34 +109,16 @@ describe('BundleForm', () => {
})

it('should show an error when the bundle already exists', () => {
// Mock the data returned by useBundles hook
const mockData: BundleDocument[] = [
{
_type: 'bundle',
_id: 'existing-bundle',
_createdAt: '2022-01-01T00:00:00Z',
authorId: 'author-id',
name: 'existing-bundle',
title: 'Existing Bundle',
icon: 'cube',
hue: 'gray',
publishAt: '2022-01-01',
_updatedAt: '',
_rev: '',
},
// Add more mock data if needed
]
mockUseBundleStore.mockReturnValue({data: mockData, loading: false, dispatch: jest.fn()})

const titleInput = screen.getByTestId('bundle-form-title')
fireEvent.change(titleInput, {target: {value: 'existing-bundle'}})
fireEvent.change(titleInput, {target: {value: 'Spring Drop'}})

expect(screen.getByTestId('input-validation-icon-error')).toBeInTheDocument()
})

it('should show an error when the title is empty', () => {
const titleInput = screen.getByTestId('bundle-form-title')
fireEvent.change(titleInput, {target: {value: ' '}})
fireEvent.change(titleInput, {target: {value: 'test'}}) // Set a valid title first
fireEvent.change(titleInput, {target: {value: ' '}}) // remove the title

expect(screen.getByTestId('input-validation-icon-error')).toBeInTheDocument()
})
Expand Down

0 comments on commit 208dffc

Please sign in to comment.