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 for userform component #49

Merged
merged 11 commits into from
Oct 20, 2023
24 changes: 18 additions & 6 deletions frontend/src/components/UserForm/UserForm.jsx
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eliminar console.log
El sendPlayerName puede fallar, deberia estar dentro de el try

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {useFormik} from 'formik';
import {useDispatch, useSelector} from 'react-redux';
import {setPlayerId, setPlayerName, setPlayerLogedIn} from '../../appActions';
// eslint-disable-next-line no-unused-vars
import React from 'react';
import React, {useState} from 'react';
import {Link} from 'react-router-dom';
import sendPlayerName from '../request/sendPlayerName';
// import SendPlayerName from '../request/sendPlayerName.mock';
Expand All @@ -12,21 +12,24 @@ const UserForm = () => {
const dispatch = useDispatch();
const firstPlayer = useSelector((state) => state.player);
const initialValues = {username: ''};
const [alertMessage, setAlertMessage] = useState(''); // State for alert message

const onSubmit = async (values) => {
// console.log('onSubmit called'); // Add this line

const actualPlayer = {name: values.username, id: 0};
const resp = await sendPlayerName({player: actualPlayer});
try {
const resp = await sendPlayerName({player: actualPlayer});
const updatedPlayer = {name: resp.name, id: resp.id};
dispatch(setPlayerId(updatedPlayer.id));
dispatch(setPlayerName(updatedPlayer.name));
// console.log('Setting success message:', 'Success: ' + resp.detail);
setAlertMessage('Success: ' + resp.detail); // Set success message
dispatch(setPlayerLogedIn(true));
alert('Succes: ' + resp.detail);
} catch (error) {
// The status code is missing in the response
console.error('Error: ' + error);
if (!error.ok) {
alert(error.detail);
setAlertMessage(error.detail); // Set error message
}
formik.resetForm();
}
Expand All @@ -47,10 +50,19 @@ const UserForm = () => {
});
return (
<div>
{alertMessage && (
<div
className={`alert ${
alertMessage.includes('Success') ? 'success' : 'error'
}`}
>
{alertMessage}
</div>
)}
<form onSubmit={formik.handleSubmit}>
{!firstPlayer.loged ? (
<div className='form/control'>
<h1>Choose a nickname </h1>
<h1>Choose a nickname</h1>
<label htmlFor='username'>User Name</label>
<input
type='text'
Expand Down
132 changes: 132 additions & 0 deletions frontend/src/components/UserForm/UserForm.test.js
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

En los mocks si el ok es true el status deberia ser 200
400 en duplacte entry y 422 en default
En el test shouldn't register hay un try con catch vacio

Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// eslint-disable-next-line no-unused-vars
import React from 'react';
import {screen, waitFor} from '@testing-library/react';
// We're using our own custom render function and not RTL's render.
import {renderWithProviders} from '../../services/providerForTest/utils-for-tests';
import UserForm from './UserForm';
// eslint-disable-next-line no-unused-vars
import {getByLabelText} from '@testing-library/dom';

import userEvent from '@testing-library/user-event';

test('correct renderig of User form', () => {
renderWithProviders(<UserForm />);
const submitText = screen.getByText('Submit');
expect(submitText).toBeInTheDocument();

const userNameText = screen.getByText('User Name');
expect(userNameText).toBeInTheDocument();
});

jest.mock('../request/sendPlayerName', () => {
return {
__esModule: true,
default: async ({player}) => {
player.id = 21;

// console.log('estoy entrando en el mock');
// console.log(player);
if (player.name === 'username') {
// console.log('estoy entrando por succes en el mock');
return {
status: undefined,
ok: true,
id: 21,
name: 'username',
detail: 'User username registered successfully',
};
} else if (player.name === 'username1') {
// Simulate an error by rejecting the promise
// console.log('estoy entrando por reject en el mock');
return {
status: undefined,
ok: false,
detail:
'Object Player cannot be stored in the database. IntegrityError: 1062 Duplicate entry "username1" for key "player.name"',
};
} else {
// Handle other cases as needed
// console.log('estoy entrando por oytros en el mock');
return {
status: undefined,
ok: false,
detail: 'Some default error message',
};
}
},
};
});

test('should register', async () => {
const user = userEvent.setup();
const screen = renderWithProviders(<UserForm />);
const usernameInput = screen.getByLabelText('User Name');

expect(usernameInput).toBeInTheDocument();
// Focus on the input field and type the username

user.click(usernameInput);
user.type(usernameInput, 'username');

// Use await waitFor to handle asynchronous updates
await waitFor(() => {
expect(usernameInput).toHaveValue('username');
});
// Click the submit button
const submitButton = screen.getByRole('button', {name: /submit/i});
expect(submitButton).toBeInTheDocument();

user.click(submitButton);
// Wait for the success message

await waitFor(() =>
screen.getByText(/ User username registered successfully/i),
);

// Assert that the success message is present
expect(
screen.getByText(/ User username registered successfully/i),
).toBeInTheDocument();
});

test('shouldnt register', async () => {
const user = userEvent.setup();

const screen = renderWithProviders(<UserForm />);
const usernameInput = screen.getByLabelText('User Name');

expect(usernameInput).toBeInTheDocument();
// Focus on the input field and type the username

user.click(usernameInput);
user.type(usernameInput, 'username1');

// Use await waitFor to handle asynchronous updates
await waitFor(() => {
expect(usernameInput).toHaveValue('username1');
});
// Click the submit button
const submitButton = screen.getByRole('button', {name: /submit/i});
expect(submitButton).toBeInTheDocument();

try {
user.click(submitButton);
} catch (error) {
// console.log('estoy entrando en el catch');
/// /console.log(screen.debug());
// console.log(error);
}

await waitFor(() =>
screen.getByText(
/Object Player cannot be stored in the database. IntegrityError: 1062 Duplicate entry "username1" for key "player.name"/i,
),
);

// Assert that the success message is present
expect(
screen.getByText(
/Object Player cannot be stored in the database. IntegrityError: 1062 Duplicate entry "username1" for key "player.name"/i,
),
).toBeInTheDocument();
});