Skip to content

Commit

Permalink
Merge pull request #238 from Arquisoft/front_end_rita
Browse files Browse the repository at this point in the history
more test for webapp
  • Loading branch information
sergiollende authored Apr 28, 2024
2 parents 9badf3e + 899363e commit e492fe2
Show file tree
Hide file tree
Showing 5 changed files with 155 additions and 2 deletions.
31 changes: 31 additions & 0 deletions webapp/src/components/general/SimpleNav.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,37 @@ describe('SimpleNav', () => {
expect(getByTestId('audio-button')).toBeInTheDocument();
});

test('renders audio button', () => {
const { getByTestId } = render(
<Router>
<SimpleNav />
</Router>
);

// Check if audio button is rendered
expect(getByTestId('audio-button')).toBeInTheDocument();
});

test('toggle audio playback', () => {
// Mock useRef hook
jest.spyOn(React, 'useRef').mockReturnValueOnce({
current: {
play: jest.fn(),
pause: jest.fn()
}
});

// Render SimpleNav component
const { getByTestId } = render(<Router> <SimpleNav /> </Router>);

// Click on audio button
fireEvent.click(getByTestId('audio-button'));

// Click on audio button again
fireEvent.click(getByTestId('audio-button'));
});


/*test('toggles audio playback when button is clicked', () => {
const { getByTestId } = render(<Router> <SimpleNav /> </Router>);
Expand Down
19 changes: 19 additions & 0 deletions webapp/src/components/leaderboard/RankingTable.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,23 @@ describe('RankingTable', () => {
expect(percentageUser1).toHaveTextContent('50%');
expect(percentageUser2).toHaveTextContent('30%');
});

it('handles error during user retrieval', async () => {
// Mock the getAllUsers function to simulate an error
(getAllUsers as jest.Mock).mockRejectedValue(new Error('Failed to retrieve users'));

// Spy on console.error to check if it's called with the expected error message
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});

await act(async () => {
render(<RankingTable />);
});

// Check if console.error was called with the expected error message
expect(consoleErrorSpy).toHaveBeenCalledWith('Error during retrieving all the users', expect.any(Error));

// Restore the original console.error implementation
consoleErrorSpy.mockRestore();
});

});
29 changes: 28 additions & 1 deletion webapp/src/components/leaderboard/TrivialRankingTable.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ describe('TrivialRankingTable', () => {
await act(async () => {
render(<TrivialRankingTable />);
});
});
});

it('displays users with cheeseCount greater than 0', async () => {
await act(async () => {
Expand All @@ -45,4 +45,31 @@ describe('TrivialRankingTable', () => {
expect(users[0]).toHaveTextContent('user2');
expect(users[1]).toHaveTextContent('user1');
});

it('logs error message when getAllUsers fails', async () => {
const consoleErrorSpy = jest.spyOn(console, 'error');
const errorMessage = 'Error during retrieving all the users';
const error = new Error('Test error');
(getAllUsers as jest.Mock).mockRejectedValue(error);

await act(async () => {
render(<TrivialRankingTable />);
});
await waitFor(() => expect(getAllUsers).toHaveBeenCalled());

expect(consoleErrorSpy).toHaveBeenCalledWith(errorMessage, error);
});

it('does not render table when getAllUsers fails', async () => {
const errorMessage = 'Error during retrieving all the users';
const error = new Error('Test error');
(getAllUsers as jest.Mock).mockRejectedValue(error);

await act(async () => {
render(<TrivialRankingTable />);
});

expect(screen.queryByTestId('user-row')).not.toBeInTheDocument();
expect(screen.queryByText(errorMessage)).not.toBeInTheDocument();
});
});
29 changes: 28 additions & 1 deletion webapp/src/components/stats/Statistics.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ jest.mock('../../stores/user-store');
jest.mock('../../services/auth-service');

describe('Statistics component', () => {
let originalConsoleError;

beforeAll(() => {
// Guardar la función original de console.error
originalConsoleError = console.error;
// Sustituir console.error con una función mock
console.error = jest.fn();
});

it('renders user information correctly', async () => {
const mockUser = { username: 'testuser', email: '[email protected]' };
(useUserStore.getState as jest.Mock).mockReturnValue({ user: mockUser });
Expand All @@ -23,4 +32,22 @@ describe('Statistics component', () => {
expect(screen.getByText(mockUser.username)).toBeInTheDocument();
expect(screen.getByText(mockUser.email)).toBeInTheDocument();
});
});



it('handles error during user retrieval', async () => {
const errorMessage = 'Failed to retrieve user';
const mockError = new Error(errorMessage);
(useUserStore.getState as jest.Mock).mockReturnValue({ user: { username: 'testuser' } });
(getUser as jest.Mock).mockRejectedValue(mockError);

await act(async () => {
render(<Router>
<Statistics />
</Router>);
});

// Verifica que console.error haya sido llamado con el mensaje de error correcto
expect(console.error).toHaveBeenCalledWith('Error during retrieving the user', mockError);
});
});
49 changes: 49 additions & 0 deletions webapp/src/services/question-service.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import axios from 'axios';
import { getQuestionsFromApi, getEasyString, getHardString } from './question-service';

// Mockear axios
jest.mock('axios');

describe('getQuestionsFromApi function', () => {
it('fetches questions from API and returns data', async () => {
// Datos de ejemplo que quieres que devuelva el mock de axios
const mockedData = [
{
text: 'Example question',
answers: ['Answer 1', 'Answer 2', 'Answer 3'],
correctAnswer: 0,
wikiLink: 'https://example.com'
}
// Puedes agregar más datos de ejemplo si lo deseas
];

// Mockear la función axios.get para que devuelva los datos de ejemplo
(axios.get as jest.MockedFunction<typeof axios.get>).mockResolvedValueOnce({ data: mockedData });

// Llamar a la función que quieres probar
const questions = await getQuestionsFromApi();

// Verificar que axios.get haya sido llamado con la URL correcta
expect(axios.get).toHaveBeenCalledWith('http://localhost:8000/GetQuestions');

// Verificar que la función retorna los datos esperados
expect(questions).toEqual(mockedData);
});


});

describe('getEasyString function', () => {
it('returns the string "easy"', () => {
const result = getEasyString();
expect(result).toBe('easy');
});
});

describe('getHardString function', () => {
it('returns the string "hard"', () => {
const result = getHardString();
expect(result).toBe('hard');
});

});

0 comments on commit e492fe2

Please sign in to comment.