level_0
int64
6
10k
index
int64
0
0
repo_id
stringlengths
16
148
file_path
stringlengths
33
188
content
stringlengths
17
26.8M
9,968
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/StickyHeader.test.tsx
import '@testing-library/jest-dom'; import { act, fireEvent, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import StickyHeader from 'components/StickyHeader/StickyHeader'; import Token from 'utils/token'; import { UserType } from 'utils/role'; import Global from 'global/global'; const userName = 'prueba'; const roleUser = UserType.USER; jest.spyOn(Token, 'getTokenUsername').mockReturnValue(userName); jest.spyOn(Token, 'getTokenRole').mockReturnValue(roleUser); const userMockFetch = { name: userName, photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [], playlists: [], saved_playlists: [], }; global.fetch = jest.fn((url: string) => { if (url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}`) { return Promise.resolve({ json: () => userMockFetch, status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; test('Render StickyHeader and get User data', async () => { const component = await act(() => { return render( <MemoryRouter initialEntries={[`/location`]}> <Routes> <Route path="/location" element={<StickyHeader handleLogout={jest.fn()} />} /> </Routes> </MemoryRouter> ); }); expect(component).toBeTruthy(); }); test('StickyHeader open ContextMenuProfile', async () => { const component = await act(() => { return render( <MemoryRouter initialEntries={[`/location`]}> <Routes> <Route path="/location" element={<StickyHeader handleLogout={jest.fn()} />} /> </Routes> </MemoryRouter> ); }); const imageIconProfile = component.getByAltText('profile-icon'); await act(async () => { fireEvent.click(imageIconProfile); }); expect(component.queryByText('Cerrar sesión')).toBeInTheDocument(); expect(component.queryByText('Perfil')).toBeInTheDocument(); });
9,969
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/ContextMenu/ContextMenuPlaylist.test.tsx
import '@testing-library/jest-dom'; import '@testing-library/jest-dom/extend-expect'; import { act, fireEvent, render } from '@testing-library/react'; import ContextMenuPlaylist from 'components/AdvancedUIComponents/ContextMenu/Playlist/ContextMenuPlaylist'; import Global from 'global/global'; import { BrowserRouter } from 'react-router-dom'; import { UserType } from 'utils/role'; import Token from 'utils/token'; import * as router from 'react-router'; const playlistName = 'playlisttest'; const songName = 'songName'; const userName = 'prueba'; const roleUser = UserType.ARTIST; const artistMockFetch = { name: userName, photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], uploaded_songs: [songName], }; const playlistDTOMockFetch = { name: playlistName, photo: 'playlist', description: 'des', upload_date: 'date', owner: userName, song_names: [], }; /* const songMockFetch = { name: songName, artist: userName, photo: 'photo', duration: '180', genre: 'Rock', number_of_plays: 2, }; */ const navigate = jest.fn(); jest.spyOn(router, 'useNavigate').mockImplementation(() => navigate); jest.spyOn(Token, 'getTokenUsername').mockReturnValue(userName); jest.spyOn(Token, 'getTokenRole').mockReturnValue(roleUser); global.fetch = jest.fn((url: string, options: any) => { if ( url === `${Global.backendBaseUrl}playlists/dto/${playlistDTOMockFetch.name}` ) { return Promise.resolve({ json: () => playlistDTOMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}playlists/multiple/${playlistName}`) { return Promise.resolve({ json: () => Promise.resolve({ playlists: [JSON.stringify(playlistDTOMockFetch)], }), status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (options && options.method) { if (options.method === 'DELETE') { return Promise.resolve({ json: () => {}, status: 202, }).catch((error) => { console.log(error); }); } if (options.method === 'PUT') { return Promise.resolve({ json: () => {}, status: 204, }).catch((error) => { console.log(error); }); } if (options.method === 'POST') { return Promise.resolve({ json: () => artistMockFetch, status: 201, }).catch((error) => { console.log(error); }); } } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; test('Render ContextMenuPlaylist', async () => { const component = await act(() => { return render( <BrowserRouter> <ContextMenuPlaylist playlistName={playlistName} owner={artistMockFetch.name} handleCloseParent={jest.fn()} refreshPlaylistData={jest.fn()} refreshSidebarData={jest.fn()} /> </BrowserRouter> ); }); expect(component).toBeTruthy(); }); test('ContextMenuPlaylist delete Playlist success', async () => { const refreshSidebarDataMock = jest.fn(); const component = await act(() => { return render( <BrowserRouter> <ContextMenuPlaylist playlistName={playlistName} owner={artistMockFetch.name} handleCloseParent={jest.fn()} refreshPlaylistData={jest.fn()} refreshSidebarData={refreshSidebarDataMock} /> </BrowserRouter> ); }); const deleteButton = component.getByText('Eliminar'); if (deleteButton) { await act(async () => { fireEvent.click(deleteButton); }); } expect(refreshSidebarDataMock).toHaveBeenCalled(); }); test('ContextMenuPlaylist Add Playlist to Playlist', async () => { const refreshSidebarDataMock = jest.fn(); const component = await act(() => { return render( <BrowserRouter> <ContextMenuPlaylist playlistName={playlistName} owner={artistMockFetch.name} handleCloseParent={jest.fn()} refreshPlaylistData={jest.fn()} refreshSidebarData={refreshSidebarDataMock} /> </BrowserRouter> ); }); const addToOtherPlaylistButton = component.getByText('Añadir a otra lista'); if (addToOtherPlaylistButton) { await act(async () => { fireEvent.click(addToOtherPlaylistButton); }); } const playlistButton = component.getByText(playlistName); if (playlistButton) { await act(async () => { fireEvent.click(playlistButton); }); } expect(component.queryByText('Canciones añadidas')).toBeInTheDocument(); });
9,970
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/ContextMenu/ContextMenuSong.test.tsx
import '@testing-library/jest-dom'; import '@testing-library/jest-dom/extend-expect'; import { act, fireEvent, render } from '@testing-library/react'; import ContextMenuSong from 'components/AdvancedUIComponents/ContextMenu/Song/ContextMenuSong'; import Global from 'global/global'; import { UserType } from 'utils/role'; import Token from 'utils/token'; const playlistName = 'playlisttest'; const songName = 'songName'; const userName = 'prueba'; const roleUser = UserType.ARTIST; const artistMockFetch = { name: userName, photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], uploaded_songs: [songName], }; const playlistDTOMockFetch = { name: playlistName, photo: 'playlist', description: 'des', upload_date: 'date', owner: userName, song_names: [], }; /* const songMockFetch = { name: songName, artist: userName, photo: 'photo', duration: '180', genre: 'Rock', number_of_plays: 2, }; */ jest.spyOn(Token, 'getTokenUsername').mockReturnValue(userName); jest.spyOn(Token, 'getTokenRole').mockReturnValue(roleUser); global.fetch = jest.fn((url: string, options: any) => { if ( url === `${Global.backendBaseUrl}playlists/dto/${playlistDTOMockFetch.name}` ) { return Promise.resolve({ json: () => playlistDTOMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}playlists/multiple/${playlistName}`) { return Promise.resolve({ json: () => Promise.resolve({ playlists: [JSON.stringify(playlistDTOMockFetch)], }), status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (options.method === 'DELETE') { return Promise.resolve({ json: () => artistMockFetch, status: 202, }).catch((error) => { console.log(error); }); } if (options.method === 'PUT') { return Promise.resolve({ json: () => artistMockFetch, status: 204, }).catch((error) => { console.log(error); }); } if (options.method === 'POST') { return Promise.resolve({ json: () => artistMockFetch, status: 201, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; test('Render ContextMenuSong', async () => { const component = await act(() => { return render( <ContextMenuSong playlistName={playlistName} songName={songName} handleCloseParent={jest.fn()} refreshPlaylistData={jest.fn()} refreshSidebarData={jest.fn()} /> ); }); expect(component).toBeTruthy(); }); test('ContextMenuSong quitar de esta lista', async () => { const refreshPlaylistDataMock = jest.fn(); const component = await act(() => { return render( <ContextMenuSong playlistName={playlistName} songName={songName} handleCloseParent={jest.fn()} refreshPlaylistData={refreshPlaylistDataMock} refreshSidebarData={jest.fn()} /> ); }); try { const quitarListaButton = component.getByText('Quitar de esta lista'); await act(async () => { fireEvent.click(quitarListaButton); }); expect(refreshPlaylistDataMock).toHaveBeenCalled(); } catch (error) { // If an error occurs during rendering, fail the test // eslint-disable-next-line jest/no-conditional-expect expect(error).toBeUndefined(); } }); test('ContextMenuSong crear lista', async () => { const refreshSidebarMock = jest.fn(); const component = await act(() => { return render( <ContextMenuSong playlistName={playlistName} songName={songName} handleCloseParent={jest.fn()} refreshPlaylistData={jest.fn()} refreshSidebarData={refreshSidebarMock} /> ); }); try { const addToListButton = component.getByText('Añadir a la playlist'); await act(async () => { fireEvent.click(addToListButton); }); const crearListaButton = component.getByText('Crear lista'); await act(async () => { fireEvent.click(crearListaButton); }); await act(async () => { fireEvent.click(addToListButton); }); expect(refreshSidebarMock).toHaveBeenCalled(); } catch (error) { // If an error occurs during rendering, fail the test // eslint-disable-next-line jest/no-conditional-expect expect(error).toBeUndefined(); } }); test('ContextMenuSong add to playlist', async () => { const component = await act(() => { return render( <ContextMenuSong playlistName={playlistName} songName={songName} handleCloseParent={jest.fn()} refreshPlaylistData={jest.fn()} refreshSidebarData={jest.fn()} /> ); }); try { const addToListButton = component.getByText('Añadir a la playlist'); await act(async () => { fireEvent.click(addToListButton); }); const playlistButton = component.getByText(playlistName); await act(async () => { fireEvent.click(playlistButton); }); } catch (error) { // If an error occurs during rendering, fail the test // eslint-disable-next-line jest/no-conditional-expect expect(error).toBeUndefined(); } });
9,971
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/Footer/Footer.test.tsx
import '@testing-library/jest-dom'; import '@testing-library/jest-dom/extend-expect'; import { render } from '@testing-library/react'; import Footer from 'components/footer/Footer'; import { BrowserRouter } from 'react-router-dom'; test('Render footer', () => { const component = render( <BrowserRouter> <Footer songName="" /> </BrowserRouter> ); expect(component).toBeTruthy(); });
9,972
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/Footer/Player.test.tsx
import '@testing-library/jest-dom'; import '@testing-library/jest-dom/extend-expect'; import { render } from '@testing-library/react'; import Player from 'components/footer/Player/Player'; import Global from 'global/global'; import Token from 'utils/token'; import { UserType } from 'utils/role'; import { act } from 'react-test-renderer'; const songName = 'songName'; const userName = 'prueba'; const roleUser = UserType.USER; const songMockFetch = { name: songName, artist: userName, photo: 'photo', duration: '180', genre: 'Rock', number_of_plays: 2, url: 'https://5b44cf20b0388.streamlock.net:8443/vod/smil:bbb.smil/playlist.m3u8', }; jest.spyOn(Token, 'getTokenUsername').mockReturnValue(userName); jest.spyOn(Token, 'getTokenRole').mockReturnValue(roleUser); global.fetch = jest.fn((url: string) => { if (url === `${Global.backendBaseUrl}canciones/${songName}`) { return Promise.resolve({ json: () => songMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}canciones/dto/${songName}`) { return Promise.resolve({ json: () => songMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}canciones/${songName}/numberOfPlays`) { return Promise.resolve({ json: () => {}, status: 204, }).catch((error) => { console.log(error); }); } if ( url === `${Global.backendBaseUrl}usuarios/${userName}/historial?nombre_cancion=${songName}` ) { return Promise.resolve({ json: () => {}, status: 204, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; jest .spyOn(window.HTMLMediaElement.prototype, 'play') .mockImplementation(jest.fn()); jest .spyOn(window.HTMLMediaElement.prototype, 'pause') .mockImplementation(jest.fn()); /* const mockAudioPlay = jest .spyOn(window.HTMLMediaElement.prototype, 'play') .mockImplementation(jest.fn()); const mockAudioPause = jest .spyOn(window.HTMLMediaElement.prototype, 'pause') .mockImplementation(jest.fn()); */ test('Render Player', async () => { let component; await act(async () => { component = render( <Player volume={0} songName={songName} changeSongInfo={jest.fn()} /> ); }); expect(component).toBeTruthy(); });
9,973
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/Footer/SongConfig.test.tsx
import '@testing-library/jest-dom'; import '@testing-library/jest-dom/extend-expect'; import { act, fireEvent, render } from '@testing-library/react'; import SongConfig from 'components/footer/SongConfig/SongConfig'; import VolumeSlider from 'components/footer/SongConfig/VolumeSlider/VolumeSlider'; import { BrowserRouter } from 'react-router-dom'; test('Render Song Config', () => { const mockChangeVolume = jest.fn(); const component = render( <BrowserRouter> <SongConfig changeVolume={mockChangeVolume} /> </BrowserRouter> ); expect(component).toBeTruthy(); }); test('Render Volume Slider', () => { const mockChangeVolume = jest.fn(); const component = render( <BrowserRouter> <VolumeSlider changeVolume={mockChangeVolume} /> </BrowserRouter> ); expect(component).toBeTruthy(); }); test('Song config change volume', async () => { const mockChangeVolume = jest.fn(); const component = render( <BrowserRouter> <VolumeSlider changeVolume={mockChangeVolume} /> </BrowserRouter> ); const slider = component.container.querySelector('input[type="range"]'); await act(async () => { if (slider) { fireEvent.change(slider, { target: { value: 25 } }); } }); expect(mockChangeVolume).toHaveBeenCalledWith(25); }); test('Song config change volume to 0', async () => { const mockChangeVolume = jest.fn(); const component = render( <BrowserRouter> <VolumeSlider changeVolume={mockChangeVolume} /> </BrowserRouter> ); const slider = component.container.querySelector('input[type="range"]'); await act(async () => { if (slider) { fireEvent.change(slider, { target: { value: 0 } }); } }); expect(mockChangeVolume).toHaveBeenCalledWith(0); expect( component.getByTestId('songconfig-speaker-button-mute') ).toBeInTheDocument(); }); test('Volume Slider click mute', async () => { const mockChangeVolume = jest.fn(); const component = render( <BrowserRouter> <VolumeSlider changeVolume={mockChangeVolume} /> </BrowserRouter> ); const speakerButton = component.getByTestId('songconfig-speaker-button'); await act(() => { return fireEvent.click(speakerButton); }); expect( component.getByTestId('songconfig-speaker-button-mute') ).toBeInTheDocument(); });
9,974
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/Footer/SongInfo.test.tsx
import '@testing-library/jest-dom'; import '@testing-library/jest-dom/extend-expect'; import { act, fireEvent, render } from '@testing-library/react'; import SongInfo from 'components/footer/SongInfo/SongInfo'; import { BrowserRouter } from 'react-router-dom'; test('Render Song info', () => { const component = render( <BrowserRouter> <SongInfo /> </BrowserRouter> ); expect(component).toBeTruthy(); }); test('Song info click like', async () => { const component = render( <BrowserRouter> <SongInfo /> </BrowserRouter> ); const buttonLike = component.queryByTestId('songinfo-like-button'); await act(() => { if (buttonLike) { return fireEvent.click(buttonLike); } return null; }); expect(buttonLike).not.toBeInTheDocument(); }); test('Song info click unlike', async () => { const component = render( <BrowserRouter> <SongInfo /> </BrowserRouter> ); const buttonLike = component.queryByTestId('songinfo-like-button'); await act(() => { if (buttonLike) { return fireEvent.click(buttonLike); } return null; }); const buttonUnLike = component.queryByTestId('songinfo-unlike-button'); await act(() => { if (buttonUnLike) { return fireEvent.click(buttonUnLike); } return null; }); expect(buttonUnLike).not.toBeInTheDocument(); });
9,975
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/ShowAllItems
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/ShowAllItems/Items/ItemsAllArtist.test.tsx
import '@testing-library/jest-dom'; import { act, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { BrowserRouter } from 'react-router-dom'; import Global from 'global/global'; import ItemsAllArtist from 'components/ShowAllItems/Items/ItemsAllArtist'; import * as router from 'react-router'; const navigate = jest.fn(); jest.spyOn(router, 'useNavigate').mockImplementation(() => navigate); test('Render ItemsAllArtist', async () => { global.fetch = jest.fn((url: string) => { if (url === `${Global.backendBaseUrl}artistas/`) { return Promise.resolve({ json: () => Promise.resolve({ artists: [ JSON.stringify({ name: 'name', photo: 'photo', register_date: 'date', password: 'pass', playback_history: [], playlists: [], saved_playlists: [], }), ], }), status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <BrowserRouter> <ItemsAllArtist /> </BrowserRouter> ); }); expect(component).toBeTruthy(); const artistCardName = component.queryByText('name'); expect(artistCardName).toBeInTheDocument(); });
9,976
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/ShowAllItems
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/ShowAllItems/Items/ItemsAllPlaylist.test.tsx
import '@testing-library/jest-dom'; import { act, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { BrowserRouter } from 'react-router-dom'; import Global from 'global/global'; import * as router from 'react-router'; import ItemsAllPlaylists from 'components/ShowAllItems/Items/ItemsAllPlaylists'; const navigate = jest.fn(); jest.spyOn(router, 'useNavigate').mockImplementation(() => navigate); const playlistName = 'playlisttest'; const playlistDTOMockFetch = { name: playlistName, photo: 'playlist', description: 'des', upload_date: 'date', owner: 'owner', song_names: [], }; test('Render itemsAllPlaylist', async () => { global.fetch = jest.fn((url: string) => { if (url === `${Global.backendBaseUrl}playlists/`) { return Promise.resolve({ json: () => Promise.resolve({ playlists: [ JSON.stringify({ name: playlistName, photo: 'photo', description: 'description', upload_date: 'date', owner: 'owner', songs: [], }), ], }), status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <BrowserRouter> <ItemsAllPlaylists refreshSidebarData={jest.fn()} id={playlistDTOMockFetch.name} /> </BrowserRouter> ); }); expect(component).toBeTruthy(); const playlistCardName = component.queryByText(playlistDTOMockFetch.name); expect(playlistCardName).toBeInTheDocument(); });
9,977
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/ShowAllItems
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/ShowAllItems/Items/ItemsAllPlaylistFromUser.test.tsx
import '@testing-library/jest-dom'; import { act, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { BrowserRouter } from 'react-router-dom'; import Global from 'global/global'; import ItemsAllPlaylistsFromUser from 'components/ShowAllItems/Items/ItemsAllPlaylistFromUser'; import { UserType } from 'utils/role'; const playlistName = 'playlisttest'; const songName = 'songName'; const artistMockFetch = { name: 'name', photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], uploaded_songs: [songName], }; const playlistDTOMockFetch = { name: playlistName, photo: 'playlist', description: 'des', upload_date: 'date', owner: 'owner', song_names: [], }; test('Render itemsAllPlaylistFromUser', async () => { global.fetch = jest.fn(async (url: string) => { if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}playlists/multiple/${playlistName}`) { return Promise.resolve({ json: () => Promise.resolve({ playlists: [JSON.stringify(playlistDTOMockFetch)], }), status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <BrowserRouter> <ItemsAllPlaylistsFromUser userName={artistMockFetch.name} userType={UserType.ARTIST} refreshSidebarData={jest.fn()} id={artistMockFetch.name} /> </BrowserRouter> ); }); expect(component).toBeTruthy(); const playlistCardName = component.queryByText(playlistDTOMockFetch.name); expect(playlistCardName).toBeInTheDocument(); });
9,978
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/ShowAllItems
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/ShowAllItems/Items/ItemsAllSongsFromArtist.test.tsx
import '@testing-library/jest-dom'; import { act, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { BrowserRouter } from 'react-router-dom'; import Global from 'global/global'; import ItemsAllSongsFromArtist from 'components/ShowAllItems/Items/ItemsAllSongsFromArtist'; const playlistName = 'playlisttest'; const songName = 'songName'; const artistMockFetch = { name: 'name', photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], uploaded_songs: [songName], }; const songMockFetch = { name: songName, artist: 'artist', photo: 'photo', duration: '3', genre: 'Rock', number_of_plays: 2, }; test('Render items All Songs from Artist', async () => { global.fetch = jest.fn((url: string) => { if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}canciones/dto/${songName}`) { return Promise.resolve({ json: () => songMockFetch, status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <BrowserRouter> <ItemsAllSongsFromArtist artistName={artistMockFetch.name} refreshSidebarData={jest.fn()} changeSongName={jest.fn()} id={artistMockFetch.name} /> </BrowserRouter> ); }); expect(component).toBeTruthy(); const songCardName = component.queryByText(songMockFetch.name); expect(songCardName).toBeInTheDocument(); });
9,979
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/Sidebar/AddSongPlayListAccordion.test.tsx
import '@testing-library/jest-dom'; import { act, fireEvent, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { BrowserRouter } from 'react-router-dom'; import Global from 'global/global'; import Token from 'utils/token'; import { UserType } from 'utils/role'; import AddSongPlayListAccordion from 'components/Sidebar/ModalAddSongPlaylist/Accordion/AddSongPlayListAccordion'; const userName = 'prueba'; const roleUser = UserType.ARTIST; jest.spyOn(Token, 'getTokenUsername').mockReturnValue(userName); jest.spyOn(Token, 'getTokenRole').mockReturnValue(roleUser); test('render AddSongPlaylistAccordion', async () => { const handleCloseMock = jest.fn(); const reloadSidebarMock = jest.fn(); const setIsCloseAllowed = jest.fn(); global.fetch = jest.fn(async (url: string) => { if (url === `${Global.backendBaseUrl}generos/`) { return Promise.resolve({ json: () => JSON.stringify({ Rock: 'Rock', Pop: 'Pop' }), status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <BrowserRouter> <AddSongPlayListAccordion handleClose={handleCloseMock} reloadSidebar={reloadSidebarMock} setIsCloseAllowed={setIsCloseAllowed} /> </BrowserRouter> ); }); expect(component).toBeTruthy(); }); test('AddSongPlaylistAccordion submit playlist correct', async () => { const handleCloseMock = jest.fn(); const reloadSidebarMock = jest.fn(); const setIsCloseAllowed = jest.fn(); global.fetch = jest.fn(async (url: string) => { if (url === `${Global.backendBaseUrl}generos/`) { return Promise.resolve({ json: () => JSON.stringify({ Rock: 'Rock', Pop: 'Pop' }), status: 200, }).catch((error) => { console.log(error); }); } return Promise.resolve({ json: () => {}, status: 201, }).catch((error) => { console.log(error); }); }) as jest.Mock; const component = await act(() => { return render( <BrowserRouter> <AddSongPlayListAccordion handleClose={handleCloseMock} reloadSidebar={reloadSidebarMock} setIsCloseAllowed={setIsCloseAllowed} /> </BrowserRouter> ); }); const accordionExpandPlaylist = component.getByTestId( 'accordion-expand-submit-playlist' ); await act(async () => { fireEvent.click(accordionExpandPlaylist); }); expect( component.getByText('Crear lista de reproducción') ).toBeInTheDocument(); const inputName = component.getByPlaceholderText('Nombre de la playlist'); const inputPhoto = component.getByPlaceholderText( 'URL de la miniatura de la playlist' ); const inputDescripcion = component.getByPlaceholderText( 'Descripción de la playlist' ); fireEvent.change(inputName, { target: { value: 'testuser' }, }); fireEvent.change(inputPhoto, { target: { value: 'testpassword' }, }); fireEvent.change(inputDescripcion, { target: { value: 'testfoto' }, }); const submitPlaylistButton = component.getByTestId( 'sidebar-addsongplaylistaccordion-submit-playlist' ); await act(async () => { fireEvent.click(submitPlaylistButton); }); expect(component.getByText('Playlist Añadida')).toBeInTheDocument(); }); test('AddSongPlaylistAccordion submit song correct', async () => { const handleCloseMock = jest.fn(); const reloadSidebarMock = jest.fn(); const setIsCloseAllowed = jest.fn(); global.fetch = jest.fn(async (url: string) => { if (url === `${Global.backendBaseUrl}generos/`) { return Promise.resolve({ json: () => JSON.stringify({ Rock: 'Rock', Pop: 'Pop' }), status: 200, }).catch((error) => { console.log(error); }); } return Promise.resolve({ json: () => {}, status: 201, }).catch((error) => { console.log(error); }); }) as jest.Mock; const component = await act(() => { return render( <BrowserRouter> <AddSongPlayListAccordion handleClose={handleCloseMock} reloadSidebar={reloadSidebarMock} setIsCloseAllowed={setIsCloseAllowed} /> </BrowserRouter> ); }); const accordionExpandSong = component.getByTestId( 'accordion-expand-submit-song' ); await act(async () => { fireEvent.click(accordionExpandSong); }); expect(component.getByText('Subir canción')).toBeInTheDocument(); const inputName = component.getByPlaceholderText('Nombre de la canción'); const inputPhoto = component.getByPlaceholderText( 'URL de la miniatura de la playlist' ); const eligeUnGeneroOption = component.getByText('❗ Elige un género'); // Find the file input element by its name or other suitable selector const fileInputElement = component.getByTestId('sidebar-file-input'); // Create a sample file const file = new File(['(⌐□_□)'], 'sample.mp3', { type: 'audio/mp3' }); fireEvent.change(inputName, { target: { value: 'testuser' }, }); fireEvent.change(inputPhoto, { target: { value: 'testpassword' }, }); // Simulate selecting an option fireEvent.change(eligeUnGeneroOption, { target: { value: 'Rock' }, }); fireEvent.change(fileInputElement, { target: { files: [file] } }); const submitSongButton = component.getByTestId( 'sidebar-addsongplaylistaccordion-submit-song' ); await act(async () => { fireEvent.click(submitSongButton); }); expect(component.getByText('Canción Añadida')).toBeInTheDocument(); });
9,980
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/Sidebar/Playlist.test.tsx
import '@testing-library/jest-dom'; import { act, fireEvent, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { BrowserRouter } from 'react-router-dom'; import Global from 'global/global'; import Token from 'utils/token'; import { UserType } from 'utils/role'; import Playlist from 'components/Sidebar/Playlist/Playlist'; const playlistName = 'playlisttest'; const songName = 'songName'; const userName = 'prueba'; const roleUser = UserType.ARTIST; const artistMockFetch = { name: userName, photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], uploaded_songs: [songName], }; const playlistDTOMockFetch = { name: playlistName, photo: 'playlist', description: 'des', upload_date: 'date', owner: userName, song_names: [], }; jest.spyOn(Token, 'getTokenUsername').mockReturnValue(userName); jest.spyOn(Token, 'getTokenRole').mockReturnValue(roleUser); test('render Sidebar Playlist', async () => { const handleUrlPlaylistClicked = () => jest.fn(); const reloadSidebar = () => jest.fn(); const component = await act(() => { return render( <BrowserRouter> <Playlist name={playlistDTOMockFetch.name} photo={playlistDTOMockFetch.photo} owner={artistMockFetch.name} playlistStyle="" handleUrlPlaylistClicked={handleUrlPlaylistClicked} reloadSidebar={reloadSidebar} /> </BrowserRouter> ); }); expect(component).toBeTruthy(); expect(component.queryByText(playlistName)).toBeInTheDocument(); }); test('Sidebar Playlist handle open context menu', async () => { const handleUrlPlaylistClickedMock = jest.fn(); const reloadSidebarMock = jest.fn(); global.fetch = jest.fn(async (url: string) => { if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}playlists/multiple/${playlistName}`) { return Promise.resolve({ json: () => Promise.resolve({ playlists: [JSON.stringify(playlistDTOMockFetch)], }), status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <BrowserRouter> <Playlist name={playlistDTOMockFetch.name} photo={playlistDTOMockFetch.photo} owner={artistMockFetch.name} playlistStyle="" handleUrlPlaylistClicked={handleUrlPlaylistClickedMock} reloadSidebar={reloadSidebarMock} /> </BrowserRouter> ); }); const playlistItemClickable = component.getByTestId( 'sidebar-playlist-wrapper' ); await act(async () => { fireEvent.contextMenu(playlistItemClickable); }); expect(component.getByText('Crear lista similar')).toBeInTheDocument(); }); test('Sidebar Playlist left-click', async () => { const handleUrlPlaylistClickedMock = jest.fn(); const reloadSidebarMock = jest.fn(); global.fetch = jest.fn(async (url: string) => { if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}playlists/multiple/${playlistName}`) { return Promise.resolve({ json: () => Promise.resolve({ playlists: [JSON.stringify(playlistDTOMockFetch)], }), status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <BrowserRouter> <Playlist name={playlistDTOMockFetch.name} photo={playlistDTOMockFetch.photo} owner={artistMockFetch.name} playlistStyle="" handleUrlPlaylistClicked={handleUrlPlaylistClickedMock} reloadSidebar={reloadSidebarMock} /> </BrowserRouter> ); }); const playlistItemClickable = component.getByTestId( 'sidebar-playlist-wrapper' ); await act(async () => { fireEvent.click(playlistItemClickable); }); expect(handleUrlPlaylistClickedMock).toHaveBeenCalledWith(playlistName); });
9,981
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/components/Sidebar/Sidebar.test.tsx
import '@testing-library/jest-dom'; import { act, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { BrowserRouter } from 'react-router-dom'; import Global from 'global/global'; import Sidebar from 'components/Sidebar/Sidebar'; import Token from 'utils/token'; import { UserType } from 'utils/role'; const playlistName = 'playlisttest'; const songName = 'songName'; const userName = 'prueba'; const roleUser = UserType.ARTIST; const artistMockFetch = { name: userName, photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], uploaded_songs: [songName], }; const playlistDTOMockFetch = { name: playlistName, photo: 'playlist', description: 'des', upload_date: 'date', owner: 'owner', song_names: [], }; jest.spyOn(Token, 'getTokenUsername').mockReturnValue(userName); jest.spyOn(Token, 'getTokenRole').mockReturnValue(roleUser); test('render Sidebar', async () => { global.fetch = jest.fn(async (url: string) => { if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if ( url === `${Global.backendBaseUrl}playlists/multiple/${playlistName},${playlistName}` ) { return Promise.resolve({ json: () => Promise.resolve({ playlists: [JSON.stringify(playlistDTOMockFetch)], }), status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <BrowserRouter> <Sidebar triggerReloadSidebar /> </BrowserRouter> ); }); expect(component).toBeTruthy(); });
9,982
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/pages/Explorar.test.tsx
import '@testing-library/jest-dom'; import { act, fireEvent, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import Explorar from 'pages/Explorar/Explorar'; import { BrowserRouter } from 'react-router-dom'; import Global from 'global/global'; const playlistName = 'playlisttest'; const songName = 'songName'; const userName = 'pruebaplaylistuser'; const artistName = 'pruebaplaylistartist'; const artistMockFetch = { name: artistName, photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], uploaded_songs: [songName], }; const userMockFetch = { name: userName, photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], }; const playlistDTOMockFetch = { name: playlistName, photo: 'playlist', description: 'des', upload_date: 'date', owner: 'username fake', song_names: [], }; const songMockFetch = { name: songName, artist: 'username fake song', photo: 'photo', duration: '180', genre: 'Rock', number_of_plays: 2, }; global.fetch = jest.fn((url: string) => { if (url === `${Global.backendBaseUrl}generos/`) { return Promise.resolve({ json: () => Promise.resolve({ ROCK: 'Rock', POP: 'Pop' }), status: 200, }); } if (url === `${Global.backendBaseUrl}search/?nombre=${'prueba'}`) { return Promise.resolve({ json: () => Promise.resolve({ playlists: [JSON.stringify(playlistDTOMockFetch)], songs: [JSON.stringify(songMockFetch)], users: [JSON.stringify(userMockFetch)], artistas: [JSON.stringify(artistMockFetch)], }), status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; test('Render Explorar and get Genres', async () => { const component = await act(() => { return render( <BrowserRouter> <Explorar changeSongName={jest.fn()} refreshSidebar={jest.fn()} /> </BrowserRouter> ); }); expect(component).toBeTruthy(); }); test('Explorar filter by name', async () => { const component = await act(() => { return render( <BrowserRouter> <Explorar changeSongName={jest.fn()} refreshSidebar={jest.fn()} /> </BrowserRouter> ); }); const inputSearchBar = component.getByTestId('explorar-input-searchbar'); await act(async () => { fireEvent.change(inputSearchBar, { target: { value: 'prueba' } }); }); expect(component.getByText(playlistName)).toBeInTheDocument(); expect(component.getByText(songName)).toBeInTheDocument(); expect(component.getByText(userName)).toBeInTheDocument(); expect(component.getByText(artistName)).toBeInTheDocument(); });
9,983
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/pages/Genre.test.tsx
import '@testing-library/jest-dom'; import { act, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import Genre from 'pages/Genre/Genre'; const genreName = 'Rock'; const songMockFetch = { name: 'cancion', artist: 'artist', photo: 'photo', duration: '3', genre: 'Rock', number_of_plays: 2, }; global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({ songs: [JSON.stringify(songMockFetch)], }), status: 200, }) ) as jest.Mock; test('Render Genre with one song', async () => { const component = await act(() => { return render( <MemoryRouter initialEntries={[`/artist/${genreName}`]}> <Routes> <Route path="/artist/:id" element={ <Genre refreshSidebarData={jest.fn()} changeSongName={jest.fn()} /> } /> </Routes> </MemoryRouter> ); }); expect(component).toBeTruthy(); });
9,984
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/pages/Home.test.tsx
import '@testing-library/jest-dom'; import { act, render } from '@testing-library/react'; import * as router from 'react-router'; import '@testing-library/jest-dom/extend-expect'; import Home from 'pages/Home/Home'; import Global from 'global/global'; import { BrowserRouter } from 'react-router-dom'; const navigate = jest.fn(); beforeEach(() => { jest.spyOn(router, 'useNavigate').mockImplementation(() => navigate); }); test('render Home', async () => { global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({}), status: 200, }) ) as jest.Mock; const component = await act(() => { return render(<Home refreshSidebarData={jest.fn()} />); }); expect(component).toBeTruthy(); }); test('Home fields', async () => { global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({}), status: 200, }) ) as jest.Mock; const component = await act(() => { return render(<Home refreshSidebarData={jest.fn()} />); }); expect(component.queryByText('Especialmente para ti')).toBeInTheDocument(); expect(component.queryByText('Artistas destacados')).toBeInTheDocument(); }); test('prueba', async () => { global.fetch = jest.fn((url: string) => { if (url === `${Global.backendBaseUrl}artistas/`) { return Promise.resolve({ json: () => Promise.resolve({ artists: [ JSON.stringify({ name: 'name', photo: 'photo', register_date: 'date', password: 'pass', playback_history: [], playlists: [], saved_playlists: [], }), ], }), status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}playlists/`) { return Promise.resolve({ json: () => Promise.resolve({ playlists: [ JSON.stringify({ name: 'name', photo: 'photo', description: 'description', upload_date: 'date', owner: 'owner', songs: [], }), ], }), status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <BrowserRouter> <Home refreshSidebarData={jest.fn()} /> </BrowserRouter> ); }); expect(component.queryByText('Especialmente para ti')).toBeInTheDocument(); expect(component.queryByText('Artistas destacados')).toBeInTheDocument(); });
9,985
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/pages/PlaylistArtist.test.tsx
import '@testing-library/jest-dom'; import { act, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import Playlist from 'pages/Playlist/Playlist'; import Token from 'utils/token'; import Global from 'global/global'; import { UserType } from 'utils/role'; const userName = 'prueba'; const roleArtist = UserType.ARTIST; const playlistName = 'playlisttest'; const songName = 'songName'; const artistMockFetch = { name: userName, photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], uploaded_songs: [songName], }; const playlistDTOMockFetch = { name: playlistName, photo: 'playlist', description: 'des', upload_date: 'date', owner: userName, song_names: [songName], }; const songMockFetch = { name: songName, artist: 'artist', photo: 'photo', duration: '180', genre: 'Rock', number_of_plays: 2, }; jest.spyOn(Token, 'getTokenUsername').mockReturnValue(userName); jest.spyOn(Token, 'getTokenRole').mockReturnValue(roleArtist); test('Playlist artist role get all info', async () => { global.fetch = jest.fn((url: string) => { if ( url === `${Global.backendBaseUrl}playlists/dto/${playlistDTOMockFetch.name}` ) { return Promise.resolve({ json: () => playlistDTOMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}artistas/${userName}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}canciones/dto/${songName}`) { return Promise.resolve({ json: () => songMockFetch, status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <MemoryRouter initialEntries={[`/playlist/${playlistDTOMockFetch.name}`]}> <Routes> <Route path="/playlist/:id" element={ <Playlist changeSongName={jest.fn()} triggerReloadSidebar={jest.fn()} /> } /> </Routes> </MemoryRouter> ); }); expect(component).toBeTruthy(); expect(component.container).toHaveTextContent(userName); expect(component.container).toHaveTextContent(playlistName); expect(component.container).toHaveTextContent(`0 h 3 min aproximadamente`); expect(component.container).toHaveTextContent(songMockFetch.name); });
9,986
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/pages/PlaylistUser.test.tsx
import '@testing-library/jest-dom'; import { act, fireEvent, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import Playlist from 'pages/Playlist/Playlist'; import Token from 'utils/token'; import Global from 'global/global'; import { UserType } from 'utils/role'; const userName = 'prueba'; const roleUser = UserType.USER; const playlistName = 'playlisttest'; const songName = 'songName'; const artistMockFetch = { name: userName, photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], uploaded_songs: [songName], }; const playlistDTOMockFetch = { name: playlistName, photo: 'playlist', description: 'des', upload_date: 'date', owner: userName, song_names: [songName], }; const songMockFetch = { name: songName, artist: 'artist', photo: 'photo', duration: '180', genre: 'Rock', number_of_plays: 2, }; const userMockFetch = { name: userName, photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], }; jest.spyOn(Token, 'getTokenUsername').mockReturnValue(userName); jest.spyOn(Token, 'getTokenRole').mockReturnValue(roleUser); test('Playlist user role get all info', async () => { global.fetch = jest.fn((url: string) => { if ( url === `${Global.backendBaseUrl}playlists/dto/${playlistDTOMockFetch.name}` ) { return Promise.resolve({ json: () => playlistDTOMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}canciones/dto/${songName}`) { return Promise.resolve({ json: () => songMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}`) { return Promise.resolve({ json: () => userMockFetch, status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <MemoryRouter initialEntries={[`/playlist/${playlistDTOMockFetch.name}`]}> <Routes> <Route path="/playlist/:id" element={ <Playlist changeSongName={jest.fn()} triggerReloadSidebar={jest.fn()} /> } /> </Routes> </MemoryRouter> ); }); expect(component).toBeTruthy(); expect(component.container).toHaveTextContent(userName); expect(component.container).toHaveTextContent(playlistName); expect(component.container).toHaveTextContent(`0 h 3 min aproximadamente`); expect(component.container).toHaveTextContent(songMockFetch.name); }); test('Playlist user role hit like button', async () => { global.fetch = jest.fn((url: string, options: any) => { if ( url === `${Global.backendBaseUrl}playlists/dto/${playlistDTOMockFetch.name}` ) { return Promise.resolve({ json: () => playlistDTOMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}canciones/dto/${songName}`) { return Promise.resolve({ json: () => songMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}`) { return Promise.resolve({ json: () => userMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}playlists/${playlistName}`) { return Promise.resolve({ json: () => {}, status: 204, }).catch((error) => { console.log(error); }); } if ( url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}/playlists_guardadas?nombre_playlist=${playlistName}` && options.method === 'PATCH' ) { return Promise.resolve({ json: () => {}, status: 204, }).catch((error) => { console.log(error); }); } if ( url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}/playlists_guardadas?nombre_playlist=${playlistName}` && options.method === 'DELETE' ) { return Promise.resolve({ json: () => {}, status: 202, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <MemoryRouter initialEntries={[`/playlist/${playlistDTOMockFetch.name}`]}> <Routes> <Route path="/playlist/:id" element={ <Playlist changeSongName={jest.fn()} triggerReloadSidebar={jest.fn()} /> } /> </Routes> </MemoryRouter> ); }); await act(async () => { const likeButton = component.container.querySelector( '#playlist-like-button' ); if (likeButton) { fireEvent.click(likeButton); } }); const unlikeButton = component.container.querySelector( '#playlist-unlike-button' ); expect(unlikeButton).toBeVisible(); }); test('Playlist user role get unlike button', async () => { global.fetch = jest.fn((url: string, options: any) => { if ( url === `${Global.backendBaseUrl}playlists/dto/${playlistDTOMockFetch.name}` ) { return Promise.resolve({ json: () => playlistDTOMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}canciones/dto/${songName}`) { return Promise.resolve({ json: () => songMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}`) { return Promise.resolve({ json: () => userMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}playlists/${playlistName}`) { return Promise.resolve({ json: () => {}, status: 204, }).catch((error) => { console.log(error); }); } if ( url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}/playlists_guardadas?nombre_playlist=${playlistName}` && options.method === 'PATCH' ) { return Promise.resolve({ json: () => {}, status: 204, }).catch((error) => { console.log(error); }); } if ( url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}/playlists_guardadas?nombre_playlist=${playlistName}` && options.method === 'DELETE' ) { return Promise.resolve({ json: () => {}, status: 202, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <MemoryRouter initialEntries={[`/playlist/${playlistDTOMockFetch.name}`]}> <Routes> <Route path="/playlist/:id" element={ <Playlist changeSongName={jest.fn()} triggerReloadSidebar={jest.fn()} /> } /> </Routes> </MemoryRouter> ); }); await act(async () => { const unlikeButton = component.container.querySelector( '#playlist-unlike-button' ); if (unlikeButton) { fireEvent.click(unlikeButton); } }); const likeButton = component.container.querySelector('#playlist-like-button'); expect(likeButton).toBeVisible(); }); test('Playlist user role update playlist', async () => { global.fetch = jest.fn((url: string, options: any) => { if ( url === `${Global.backendBaseUrl}playlists/dto/${playlistDTOMockFetch.name}` ) { return Promise.resolve({ json: () => playlistDTOMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}canciones/dto/${songName}`) { return Promise.resolve({ json: () => songMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}`) { return Promise.resolve({ json: () => userMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}playlists/${playlistName}`) { return Promise.resolve({ json: () => {}, status: 204, }).catch((error) => { console.log(error); }); } if ( url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}/playlists_guardadas?nombre_playlist=${playlistName}` && options.method === 'PATCH' ) { return Promise.resolve({ json: () => {}, status: 204, }).catch((error) => { console.log(error); }); } if ( url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}/playlists_guardadas?nombre_playlist=${playlistName}` && options.method === 'DELETE' ) { return Promise.resolve({ json: () => {}, status: 202, }).catch((error) => { console.log(error); }); } if ( url === `${Global.backendBaseUrl}playlists/${playlistName}?foto=&descripcion=descripcion` ) { return Promise.resolve({ json: () => {}, status: 204, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const triggerReloadSidebarMock = jest.fn(); const component = await act(() => { return render( <MemoryRouter initialEntries={[`/playlist/${playlistDTOMockFetch.name}`]}> <Routes> <Route path="/playlist/:id" element={ <Playlist changeSongName={jest.fn()} triggerReloadSidebar={triggerReloadSidebarMock} /> } /> </Routes> </MemoryRouter> ); }); await act(async () => { const thumbnailPlaylist = component.getByAltText('thumbnail-playlist'); if (thumbnailPlaylist) { fireEvent.click(thumbnailPlaylist); } }); const inputName = component.getByPlaceholderText('Añade una descripción'); fireEvent.change(inputName, { target: { value: 'descripcion' }, }); expect(component.queryByText('Editar información')).toBeInTheDocument(); await act(async () => { const submitUpdateButton = component.queryByText('Guardar'); if (submitUpdateButton) { fireEvent.click(submitUpdateButton); } }); expect(triggerReloadSidebarMock).toHaveBeenCalledTimes(1); // Adjust the number based on your actual use case });
9,987
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/pages/RegisterMenu.test.tsx
import '@testing-library/jest-dom'; import { act, fireEvent, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import RegisterMenu from 'pages/StartMenu/RegisterMenu'; afterEach(() => { jest.clearAllMocks(); }); test('render RegisterMenu', () => { expect(render(<RegisterMenu setIsSigningUp={() => {}} />)).toBeTruthy(); }); test('RegisterMenu correct text', () => { const component = render(<RegisterMenu setIsSigningUp={jest.fn()} />); expect(component.container).toHaveTextContent( 'Regístrate en Spotify Electron' ); }); test('Register failed not all required inputs filled', () => { const mockSetIsSigningUp = jest.fn(); const component = render( <RegisterMenu setIsSigningUp={mockSetIsSigningUp} /> ); const registerButton = component.getByText('Registrar'); fireEvent.click(registerButton); expect( component.queryByText( 'No se han introducido todos los datos de registro obligatorios' ) ).toBeInTheDocument(); const popover = document.getElementById('button-info-popover'); expect(popover).toBeVisible(); if (popover) { fireEvent.click(popover); } fireEvent.click(document.body); expect( component.queryByText( 'No se han introducido todos los datos de registro obligatorios' ) ).toBeNull(); expect(popover).not.toBeVisible(); }); test('Register failed bad input', () => { const mockSetIsSigningUp = jest.fn(); const component = render( <RegisterMenu setIsSigningUp={mockSetIsSigningUp} /> ); const registerButton = component.getByText('Registrar'); fireEvent.click(registerButton); expect( component.queryByText( 'No se han introducido todos los datos de registro obligatorios' ) ).toBeInTheDocument(); const popover = document.getElementById('button-info-popover'); expect(popover).toBeVisible(); if (popover) { fireEvent.click(popover); } fireEvent.click(document.body); expect( component.queryByText( 'No se han introducido todos los datos de registro obligatorios' ) ).toBeNull(); expect(popover).not.toBeVisible(); }); test('Register failed different password inputs', () => { const mockSetIsSigningUp = jest.fn(); global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({}), status: 200, }) ) as jest.Mock; const component = render( <RegisterMenu setIsSigningUp={mockSetIsSigningUp} /> ); // Simulate user input const inputName = component.getByPlaceholderText('Nombre de usuario'); const inputPhoto = component.getByPlaceholderText('Foto de perfil'); const inputPassword = component.getByPlaceholderText('Contraseña'); const inputConfirmPassword = component.getByPlaceholderText( 'Confirma tu contraseña' ); fireEvent.change(inputName, { target: { value: 'testuser' }, }); fireEvent.change(inputPassword, { target: { value: 'testpassword' }, }); fireEvent.change(inputPhoto, { target: { value: 'testfoto' }, }); fireEvent.change(inputConfirmPassword, { target: { value: 'testpassworddiferente' }, }); const registerButton = component.getByText('Registrar'); fireEvent.click(registerButton); expect( component.queryByText('Las contraseñas no coinciden') ).toBeInTheDocument(); }); test('Register success', async () => { const mockSetIsSigningUp = jest.fn(); global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({}), status: 201, }) ) as jest.Mock; const component = render( <RegisterMenu setIsSigningUp={mockSetIsSigningUp} /> ); // Simulate user input const inputName = component.getByPlaceholderText('Nombre de usuario'); const inputPhoto = component.getByPlaceholderText('Foto de perfil'); const inputPassword = component.getByPlaceholderText('Contraseña'); const inputConfirmPassword = component.getByPlaceholderText( 'Confirma tu contraseña' ); fireEvent.change(inputName, { target: { value: 'testuser' }, }); fireEvent.change(inputPassword, { target: { value: 'testpassword' }, }); fireEvent.change(inputPhoto, { target: { value: 'testfoto' }, }); fireEvent.change(inputConfirmPassword, { target: { value: 'testpassword' }, }); const registerButton = component.getByText('Registrar'); await act(async () => { fireEvent.click(registerButton); }); const popover = document.getElementById('button-info-popover'); expect(popover).toBeVisible(); if (popover) { fireEvent.click(popover); } expect(mockSetIsSigningUp).toHaveBeenCalledWith(false); }); test('Change to login menu', () => { const mockSetIsSigningUp = jest.fn(); const component = render( <RegisterMenu setIsSigningUp={mockSetIsSigningUp} /> ); const regiserButton = component.getByText( 'Inicia sesión en Spotify Electron' ); fireEvent.click(regiserButton); expect(mockSetIsSigningUp).toHaveBeenCalledWith(false); });
9,988
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/pages/StartMenu.test.tsx
import '@testing-library/jest-dom'; import { act, fireEvent, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import StartMenu from 'pages/StartMenu/StartMenu'; afterEach(() => { jest.clearAllMocks(); }); test('render StartMenu', () => { expect( render(<StartMenu setIsLogged={() => {}} setIsSigningUp={() => {}} />) ).toBeTruthy(); }); test('StartMenu correct text', () => { const component = render( <StartMenu setIsLogged={jest.fn()} setIsSigningUp={jest.fn()} /> ); expect(component.container).toHaveTextContent( 'Inicia sesión en Spotify Electron' ); }); test('Login failed', () => { const mockSetIsLogged = jest.fn(); const component = render( <StartMenu setIsLogged={mockSetIsLogged} setIsSigningUp={jest.fn()} /> ); const loginButton = component.getByText('Iniciar sesión'); fireEvent.click(loginButton); expect( component.queryByText('No se ha podido iniciar sesión') ).toBeInTheDocument(); const popover = document.getElementById('button-info-popover'); expect(popover).toBeVisible(); if (popover) { fireEvent.click(popover); } fireEvent.click(document.body); expect(component.queryByText('No se ha podido iniciar sesión')).toBeNull(); expect(popover).not.toBeVisible(); }); test('Login success', async () => { const setIsLogged = jest.fn(); const setIsSigningUp = jest.fn(); global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({}), status: 200, }) ) as jest.Mock; const component = render( <StartMenu setIsLogged={setIsLogged} setIsSigningUp={setIsSigningUp} /> ); // Simulate user input const inputName = component.getByPlaceholderText('Nombre de usuario'); const inputPassword = component.getByPlaceholderText('Contraseña'); fireEvent.change(inputName, { target: { value: 'testuser' }, }); fireEvent.change(inputPassword, { target: { value: 'testpassword' }, }); const loginButton = component.getByText('Iniciar sesión'); await act(async () => { fireEvent.click(loginButton); }); expect(setIsLogged).toHaveBeenCalledWith(true); }); test('Change to register menu', () => { const mockSetIsRegistering = jest.fn(); const component = render( <StartMenu setIsLogged={jest.fn()} setIsSigningUp={mockSetIsRegistering} /> ); const regiserButton = component.getByText('Regístrate en Spotify Electron'); fireEvent.click(regiserButton); expect(mockSetIsRegistering).toHaveBeenCalledWith(true); });
9,989
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/pages/UserProfile.test.tsx
import '@testing-library/jest-dom'; import { act, render } from '@testing-library/react'; import * as router from 'react-router'; import '@testing-library/jest-dom/extend-expect'; import UserProfile from 'pages/UserProfile/UserProfile'; import { UserType } from 'utils/role'; import Global from 'global/global'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; /* afterEach(() => { jest.clearAllMocks(); }); */ const navigate = jest.fn(); beforeEach(() => { jest.spyOn(router, 'useNavigate').mockImplementation(() => navigate); }); /* jest.mock('react-router', () => ({ ...jest.requireActual('react-router'), useNavigate: jest.fn(), })); */ const artistMock = { photo: '', name: '', playlists: [], playback_history: [], uploaded_songs: [], play_count: [], }; const userMock = { photo: '', name: '', playlists: [], playback_history: [], }; test('render UserProfile with User', async () => { global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve(userMock), status: 200, }) ) as jest.Mock; const component = await act(() => { return render( <UserProfile changeSongName={jest.fn()} refreshSidebarData={jest.fn()} userType={UserType.USER} /> ); }); expect(component).toBeTruthy(); }); test('render UserProfile with Artist', async () => { global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve(artistMock), status: 200, }) ) as jest.Mock; const component = await act(() => { return render( <UserProfile changeSongName={jest.fn()} refreshSidebarData={jest.fn()} userType={UserType.USER} /> ); }); expect(component).toBeTruthy(); }); test('UserProfile User Fields', async () => { global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve(userMock), status: 200, }) ) as jest.Mock; const component = await act(() => { return render( <UserProfile changeSongName={jest.fn()} refreshSidebarData={jest.fn()} userType={UserType.USER} /> ); }); expect( component.queryByText('Historial de reproducción') ).toBeInTheDocument(); expect(component.queryByText('Playlists del usuario')).toBeInTheDocument(); }); test('UserProfile Artist Fields', async () => { global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve(artistMock), status: 200, }) ) as jest.Mock; const component = await act(() => { return render( <UserProfile changeSongName={jest.fn()} refreshSidebarData={jest.fn()} userType={UserType.ARTIST} /> ); }); expect(component.queryByText('Canciones del artista')).toBeInTheDocument(); expect(component.queryByText('Playlists del usuario')).toBeInTheDocument(); expect(component.queryByText('reproducciones totales')).toBeInTheDocument(); }); test('UserProfile User load Playback history and his Playlists', async () => { const playlistName = 'playlisttest'; const songName = 'songName'; const userMockFetch = { name: 'name', photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], }; const playlistDTOMockFetch = { name: playlistName, photo: 'playlist', description: 'des', upload_date: 'date', owner: 'owner', song_names: [songName], }; const songMockFetch = { name: songName, artist: 'artist', photo: 'photo', duration: '3', genre: 'Rock', number_of_plays: 2, }; jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useParams: () => ({ id: userMockFetch.name, }), })); global.fetch = jest.fn((url: string) => { if ( url === `${Global.backendBaseUrl}playlists/dto/${playlistDTOMockFetch.name}` ) { return Promise.resolve({ json: () => playlistDTOMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}playlists/`) { return Promise.resolve({ json: () => playlistDTOMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}usuarios/${userMockFetch.name}`) { return Promise.resolve({ json: () => userMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}canciones/dto/${songName}`) { return Promise.resolve({ json: () => songMockFetch, status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <MemoryRouter initialEntries={[`/user/${userMockFetch.name}`]}> <Routes> <Route path="/user/:id" element={ <UserProfile refreshSidebarData={jest.fn()} changeSongName={jest.fn()} userType={UserType.USER} /> } /> </Routes> </MemoryRouter> ); }); const elementsWithUserName = component.getAllByText(userMockFetch.name); expect(elementsWithUserName.length).toBeGreaterThan(0); expect(component.queryByText(songName)).toBeInTheDocument(); expect(component.queryByText(playlistName)).toBeInTheDocument(); }); test('UserProfile Artist load Songs and Playcount', async () => { const playlistName = 'playlisttest'; const songName = 'songName'; const numPlayCount = 2; const artistMockFetch = { name: 'name', photo: 'photo', register_date: 'date', password: 'hashpassword', playback_history: [songName], playlists: [playlistName], saved_playlists: [playlistName], uploaded_songs: [songName], }; const playlistDTOMockFetch = { name: playlistName, photo: 'playlist', description: 'des', upload_date: 'date', owner: 'owner', song_names: [songName], }; const songMockFetch = { name: songName, artist: 'artist', photo: 'photo', duration: '3', genre: 'Rock', number_of_plays: 2, }; jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useParams: () => ({ id: artistMockFetch.name, }), })); global.fetch = jest.fn((url: string) => { if ( url === `${Global.backendBaseUrl}playlists/dto/${playlistDTOMockFetch.name}` ) { return Promise.resolve({ json: () => playlistDTOMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}playlists/`) { return Promise.resolve({ json: () => playlistDTOMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}`) { return Promise.resolve({ json: () => artistMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if (url === `${Global.backendBaseUrl}canciones/dto/${songName}`) { return Promise.resolve({ json: () => songMockFetch, status: 200, }).catch((error) => { console.log(error); }); } if ( url === `${Global.backendBaseUrl}artistas/${artistMockFetch.name}/reproducciones` ) { return Promise.resolve({ json: () => ({ play_count: numPlayCount, }), status: 200, }).catch((error) => { console.log(error); }); } // In case the URL doesn't match, return a rejected promise return Promise.reject(new Error('Unhandled URL in fetch mock')); }) as jest.Mock; const component = await act(() => { return render( <MemoryRouter initialEntries={[`/artist/${artistMockFetch.name}`]}> <Routes> <Route path="/artist/:id" element={ <UserProfile refreshSidebarData={jest.fn()} changeSongName={jest.fn()} userType={UserType.ARTIST} /> } /> </Routes> </MemoryRouter> ); }); const elementsWithUserName = component.getAllByText(artistMockFetch.name); expect(elementsWithUserName.length).toBeGreaterThan(0); expect(component.queryByText(songName)).toBeInTheDocument(); expect(component.queryByText(playlistName)).toBeInTheDocument(); expect( component.queryByText(`${numPlayCount} reproducciones totales`) ).toBeInTheDocument(); });
9,990
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/renderer/App.test.tsx
import '@testing-library/jest-dom'; import { render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { BrowserRouter } from 'react-router-dom'; import App from '../../renderer/App'; const scrollToMock = jest.fn(); Object.defineProperty(window, 'scrollTo', { value: scrollToMock }); describe('App', () => { it('should render', () => { expect( render( <BrowserRouter> <App /> </BrowserRouter> ) ).toBeTruthy(); }); });
9,991
0
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__
petrpan-code/AntonioMrtz/SpotifyElectron/Electron/src/__tests__/utils/Token.test.tsx
import '@testing-library/jest-dom/extend-expect'; import Token from 'utils/token'; import { UserType } from 'utils/role'; const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NfdG9rZW4iOiJwcnVlYmEiLCJyb2xlIjoidXN1YXJpbyIsInRva2VuX3R5cGUiOiJiZWFyZXIiLCJleHAiOjE2OTgwNzQzNzl9.tGdFk2EhCJ3VJKmqmiduVN-d6UUS9tMeCzQ_YfJ35Qs'; const username = 'prueba'; const userType = UserType.USER; // Set up mock localStorage const mockLocalStorage = { getItem: jest.fn(() => { return token; }), }; Object.defineProperty(window, 'localStorage', { value: mockLocalStorage, }); test('Get jwt token', () => { const jwtToken = Token.getToken(); expect(token).toEqual(jwtToken); }); test('Get jwt token username', () => { const usernameJwtToken = Token.getTokenUsername(); expect(username).toEqual(usernameJwtToken); }); test('Get jwt token role', () => { const userTypeJwtToken = Token.getTokenRole(); expect(userType).toEqual(userTypeJwtToken); }); test('Get jwt header', () => { const headerJwtToken = Token.getTokenHeader(); expect({ Authorization: token }).toMatchObject(headerJwtToken); });