Skip to content

Commit

Permalink
Merge pull request #154 from wizelineacademy/PruebasSofia
Browse files Browse the repository at this point in the history
Chore: Pruebas Sofia
  • Loading branch information
Bdelas777 authored Jun 12, 2024
2 parents d8f6709 + 03a54f4 commit 0724a2d
Show file tree
Hide file tree
Showing 17 changed files with 813 additions and 36 deletions.
94 changes: 94 additions & 0 deletions cypress/e2e/GeneralData.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
describe('GeneralData E2E Test', () => {
beforeEach(() => {
// Cambia esta ruta a la ruta donde se monta tu componente
cy.visit('/home/generalData')
})

it('renders the page correctly', () => {
cy.get('h1').contains('Datos Generales').should('be.visible')
})

it('shows an error if birth date is less than 15 years ago', () => {
// Mock the API call to get health data
cy.intercept('GET', '/api/healthdata', {
statusCode: 200,
body: {
weight: 70,
sex: 'M',
bodyFat: 20,
height: 1.75,
birthDate: '2000-01-01',
muscularMass: 30,
},
}).as('getHealthData')

// Ensure the page has loaded the initial data
cy.wait('@getHealthData')

// Click the edit button
cy.get('button').contains('Editar').click()

// Try to set the birth date to a date less than 15 years ago
const currentDate = new Date()
const recentDate = new Date(
currentDate.getFullYear() - 10,
currentDate.getMonth(),
currentDate.getDate(),
)
const formattedDate = recentDate.toISOString().split('T')[0]

cy.get('input[name="birthDate"]')
.clear({ force: true })
.type(formattedDate, { force: true })

// Save the changes
cy.get('button').contains('Guardar Cambios').click()

// Check the error message
cy.on('window:alert', (text) => {
expect(text).to.contains(
'La fecha de nacimiento no puede ser menor a 15 años antes de la fecha actual',
)
})
})

it('cancels edit and restores original data', () => {
// Mock the API call to get health data
cy.intercept('GET', '/api/healthdata', {
statusCode: 200,
body: {
weight: 70,
sex: 'M',
bodyFat: 20,
height: 1.75,
birthDate: '2000-01-01',
muscularMass: 30,
},
}).as('getHealthData')

// Ensure the page has loaded the initial data
cy.wait('@getHealthData')

// Click the edit button
cy.get('button').contains('Editar').click()

// Edit the weight input
cy.get('input[name="weight"]')
.clear({ force: true })
.type('75', { force: true })

// Cancel the edit
cy.get('button').contains('Cancelar').click({ force: true })

// Verify the data has been restored
cy.get('div').contains('70').should('be.visible')
})

Cypress.on('uncaught:exception', (err) => {
// We can ignore invalid time value error
if (err.message.includes('Invalid time value')) {
return false
}
return true
})
})
46 changes: 46 additions & 0 deletions src/components/Home.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/// Home.test.tsx
import { render, screen } from '@testing-library/react'
import Home from './Home'
import { describe, it, expect, vi } from 'vitest'

// Mock de next/image
vi.mock('next/image', () => ({
__esModule: true,
default: ({ src, alt, ...props }: { src: string; alt: string }) => (
// eslint-disable-next-line @next/next/no-img-element
<img src={src} alt={alt} {...props} />
),
}))

// Mock de next/link
vi.mock('next/link', () => ({
__esModule: true,
default: ({
children,
href,
}: {
children: React.ReactNode
href: string
}) => <a href={href}>{children}</a>,
}))

describe('Home Component', () => {
it('renders information component', () => {
render(<Home />)
const infoComponent = screen.getByText('Regístrate')
expect(infoComponent).toBeInTheDocument()
})

it('renders registration button with correct link', () => {
render(<Home />)
const registerLink = screen.getByRole('link', { name: /Regístrate/i })
expect(registerLink).toHaveAttribute('href', '/signup')
})

it('renders the image with correct src and alt text', () => {
render(<Home />)
const image = screen.getByAltText('Picture of the author')
expect(image).toBeInTheDocument()
expect(image).toHaveAttribute('src', '/icons/heart.svg')
})
})
97 changes: 97 additions & 0 deletions src/components/Inputs/Select.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { render, screen, fireEvent } from '@testing-library/react'
import { describe, it, expect, vi } from 'vitest'
import Select from './Select'
import {
useForm,
FieldValues,
UseFormRegister,
FieldErrors,
} from 'react-hook-form'

interface SelectOption {
value: string
label: string
}

interface SelectProps {
id: string
label: string
options: SelectOption[]
disabled?: boolean
register: UseFormRegister<FieldValues>
errors: FieldErrors
big?: boolean
}

const mockOptions = [
{ value: 'option1', label: 'Option 1' },
{ value: 'option2', label: 'Option 2' },
]

describe('Select Component', () => {
const mockRegister: UseFormRegister<FieldValues> = vi.fn()

const renderSelect = (props: Partial<SelectProps> = {}) => {
const TestComponent: React.FC = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm()

return (
<form onSubmit={handleSubmit(vi.fn())}>
<Select
id='test-select'
label='Test Select'
options={mockOptions}
register={register}
errors={errors}
{...props}
/>
</form>
)
}

render(<TestComponent />)
}

it('renders the Select component', () => {
renderSelect()
expect(screen.getByLabelText('Test Select')).toBeInTheDocument()
})

it('renders all options', () => {
renderSelect()
fireEvent.click(screen.getByLabelText('Test Select'))
expect(screen.getByText('Option 1')).toBeInTheDocument()
expect(screen.getByText('Option 2')).toBeInTheDocument()
})

it('calls register function', () => {
renderSelect({ register: mockRegister })
expect(mockRegister).toHaveBeenCalledWith('test-select')
})

it('disables the select when disabled prop is true', () => {
renderSelect({ disabled: true })
expect(screen.getByLabelText('Test Select')).toBeDisabled()
})

it('displays error styles when errors are present', () => {
const errors: FieldErrors = {
'test-select': { message: 'Error message' } as any,
}
renderSelect({ errors })
expect(screen.getByLabelText('Test Select')).toHaveClass(
'focus:border-rose-500',
)
})

it('applies custom width when big prop is true', () => {
renderSelect({ big: true })
expect(screen.getByLabelText('Test Select')).toHaveClass(
'w-60 lg:w-[500px]',
)
})
})
11 changes: 4 additions & 7 deletions src/components/Inputs/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,16 @@ const Select: React.FC<SelectProps> = ({
))}
</select>
<label
htmlFor={id}
className={`absolute left-4 top-5 z-10 origin-[0] -translate-y-3 transform text-xs text-white duration-150 ${errors[id] ? 'text-rose-500' : 'text-white'} `}
>
{label.includes('*') ? (
<>
{label.replace('*', '')}{' '}
{/* Esto muestra el texto del label sin el asterisco (*) */}
<span className='text-custom-red'>*</span>{' '}
{/* Esto muestra solo el asterisco (*) con el color personalizado definido por la clase `text-custom-red` */}
{label.replace('*', '')} <span className='text-custom-red'>*</span>
</>
) : (
label // Si no hay asterisco, muestra el texto del label normalmente
)}{' '}
{/* Esto muestra solo el asterisco (*) con el color personalizado */}
label
)}
</label>
</div>
)
Expand Down
72 changes: 72 additions & 0 deletions src/components/Inputs/SleepTimeSelection.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// SleepTimeSelection.test.tsx
import React from 'react'
import { render, screen, fireEvent } from '@testing-library/react'
import { SleepTimeSelection } from './SleepTimeSelection'
import { expect, vi } from 'vitest'
import '@testing-library/jest-dom'

// Primera prueba: verifica que el componente se renderiza correctamente con los elementos proporcionados
test('renders component with provided time, label and day', () => {
render(
<SleepTimeSelection
time='08:00'
label='Sleep Time'
day='Hoy'
setTime={() => {}}
setDay={() => {}}
/>,
)

// Verifica que el label se renderiza
expect(screen.getByText('Sleep Time')).toBeInTheDocument()

// Verifica que el input de tiempo se renderiza con el valor correcto
expect(screen.getByDisplayValue('08:00')).toBeInTheDocument()

// Verifica que los botones se renderizan
expect(screen.getByText('Ayer')).toBeInTheDocument()
expect(screen.getByText('Hoy')).toBeInTheDocument()
})

// Segunda prueba: verifica que setTime se llama cuando el input de tiempo cambia
test('calls setTime when input changes', () => {
const setTimeMock = vi.fn()

render(
<SleepTimeSelection
time='08:00'
label='Sleep Time'
day='Hoy'
setTime={setTimeMock}
setDay={() => {}}
/>,
)

const timeInput = screen.getByDisplayValue('08:00')
fireEvent.change(timeInput, { target: { value: '09:00' } })

expect(setTimeMock).toHaveBeenCalledWith('09:00')
})

// Tercera prueba: verifica que setDay se llama cuando se hace clic en los botones
test('calls setDay when buttons are clicked', () => {
const setDayMock = vi.fn()

render(
<SleepTimeSelection
time='08:00'
label='Sleep Time'
day='Hoy'
setTime={() => {}}
setDay={setDayMock}
/>,
)

const ayerButton = screen.getByText('Ayer')
fireEvent.click(ayerButton)
expect(setDayMock).toHaveBeenCalledWith('Ayer')

const hoyButton = screen.getByText('Hoy')
fireEvent.click(hoyButton)
expect(setDayMock).toHaveBeenCalledWith('Hoy')
})
6 changes: 3 additions & 3 deletions src/components/Inputs/SleepTimeSelection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const SleepTimeSelection = ({

<div className='flex gap-x-3'>
<input
className='rounded-2xl bg-input-purple px-2 py-3 text-white md:px-10'
className='bg-input-purple rounded-2xl px-2 py-3 text-white md:px-10'
value={time}
type='time'
onChange={(e) => {
Expand All @@ -30,15 +30,15 @@ export const SleepTimeSelection = ({
onClick={() => {
setDay('Ayer')
}}
className={`${day === 'Ayer' ? 'bg-decoration-sleep-colordark' : 'bg-decoration-sleep-colorlight'} rounded-2xl px-5 py-2 hover:bg-decoration-sleep-colordark md:px-10`}
className={`${day === 'Ayer' ? 'bg-decoration-sleep-colordark' : 'bg-decoration-sleep-colorlight'} hover:bg-decoration-sleep-colordark rounded-2xl px-5 py-2 md:px-10`}
>
Ayer
</button>
<button
onClick={() => {
setDay('Hoy')
}}
className={`${day === 'Hoy' ? 'bg-decoration-sleep-colordark' : 'bg-decoration-sleep-colorlight'} rounded-2xl px-5 py-2 hover:bg-decoration-sleep-colordark md:px-10`}
className={`${day === 'Hoy' ? 'bg-decoration-sleep-colordark' : 'bg-decoration-sleep-colorlight'} hover:bg-decoration-sleep-colordark rounded-2xl px-5 py-2 md:px-10`}
>
Hoy
</button>
Expand Down
Loading

0 comments on commit 0724a2d

Please sign in to comment.