Skip to content

Commit

Permalink
🔰 fixed tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Divergent-Caesar committed Sep 29, 2024
1 parent a6f5ed1 commit fc60df3
Show file tree
Hide file tree
Showing 4 changed files with 139 additions and 158 deletions.
Original file line number Diff line number Diff line change
@@ -1,27 +1,45 @@
import { BottomNavComponent } from './bottom-nav.component';
import { MoodService } from "./../../../services/mood-service.service";
import { Router } from '@angular/router';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';

// Mocking Router with jest.Mocked<>
const mockRouter = (): jest.Mocked<Router> => ({
navigate: jest.fn() // Mock the 'navigate' method
} as any); // Cast to `any` to avoid errors from optional methods in Router

const mockMoodService = (): jest.Mocked<MoodService> => ({
getMoodColors: jest.fn().mockReturnValue({ happy: '#ff0', sad: '#00f' }),
getComponentMoodClassesDark: jest.fn().mockReturnValue({ happy: 'dark-happy', sad: 'dark-sad' }),
getCurrentMood: jest.fn().mockReturnValue('happy'),
} as any); // Cast to `any` for mocking specific methods

describe('BottomNavComponent', () => {
let component: BottomNavComponent;
let moodService: MoodService;
let router: Router;

beforeEach(() => {
// Mock the Router
router = {
navigate: jest.fn()
} as any;

// Mock the MoodService
moodService = {
getComponentMoodClasses: jest.fn().mockReturnValue([]),
getBackgroundMoodClasses: jest.fn().mockReturnValue([]),
getComponentMoodClassesDark: jest.fn().mockReturnValue([])
} as any;
let fixture: ComponentFixture<BottomNavComponent>;

let moodService: jest.Mocked<MoodService>;
let router: jest.Mocked<Router>;

beforeEach(async () => {

router = mockRouter();
moodService = mockMoodService();

// Initialize the component with the mocked router and moodService
component = new BottomNavComponent(router, moodService);
await TestBed.configureTestingModule({
imports: [BottomNavComponent],
providers: [
provideHttpClient(),
{ provide: Router, useValue: router },
MoodService,

]
}).compileComponents();

fixture = TestBed.createComponent(BottomNavComponent);
component = fixture.componentInstance;
});

it('should create', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { MobilehomeComponent } from './mobilehome.component';
import { provideHttpClient } from '@angular/common/http';

describe('MobilehomeComponent', () => {
let component: MobilehomeComponent;
let fixture: ComponentFixture<MobilehomeComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [MobilehomeComponent]
imports: [MobilehomeComponent],
providers: [
provideHttpClient()]
})
.compileComponents();

Expand Down
237 changes: 97 additions & 140 deletions Frontend/src/app/pages/profile/profile.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,177 +1,134 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ProfileComponent } from './profile.component';
import { AuthService } from '../../services/auth.service';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { of } from 'rxjs';
import { Router } from '@angular/router';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { MatDialog } from '@angular/material/dialog';
import { AuthService } from '../../services/auth.service';
import { ScreenSizeService } from '../../services/screen-size-service.service';
import { SpotifyService } from '../../services/spotify.service';
import { ProviderService } from '../../services/provider.service';
import { MoodService } from '../../services/mood-service.service';
import { of } from 'rxjs';
import { EditProfileModalComponent } from '../../components/organisms/edit-profile-modal/edit-profile-modal.component';
import { ProfileComponent } from './profile.component';

const authServiceMock = (): jest.Mocked<AuthService> => ({
currentUser: jest.fn().mockReturnValue(of({
user: {
user_metadata: { name: 'mockname', username: 'Test User', picture: 'path/to/picture' }
}
}))
}) as any;

// Mock Router
const routerMock = (): jest.Mocked<Router> => ({
navigate: jest.fn()
}) as any;

// Mock MatDialog
const matDialogMock = (): jest.Mocked<MatDialog> => ({
open: jest.fn()
}) as any;

// Mock ScreenSizeService
const screenSizeServiceMock = (): jest.Mocked<ScreenSizeService> => ({
screenSize$: of('large')
}) as any;

// Mock SpotifyService
const spotifyServiceMock = (): jest.Mocked<SpotifyService> => ({
getTopTracks: jest.fn().mockResolvedValue([
{ id: '1', text: 'Track 1', albumName: 'Album 1', imageUrl: '', secondaryText: '', previewUrl: '', spotifyUrl: '', explicit: false }
]),
getTopArtists: jest.fn().mockResolvedValue([
{ id: '1', name: 'Artist 1', imageUrl: '', spotifyUrl: '' }
]),
playTrackById: jest.fn()
}) as any;

// Mock ProviderService
const providerServiceMock = (): jest.Mocked<ProviderService> => ({
getProviderName: jest.fn().mockReturnValue('spotify')
}) as any;

// Mock MoodService
const moodServiceMock = (): jest.Mocked<MoodService> => ({
getCurrentMood: jest.fn().mockReturnValue('happy'),
getComponentMoodClasses: jest.fn().mockReturnValue({
happy: 'happy-class',
sad: 'sad-class'
})
}) as any;

describe('ProfileComponent', () => {
let component: ProfileComponent;
let fixture: ComponentFixture<ProfileComponent>;
let authServiceMock: any;
let spotifyServiceMock: any;
let providerServiceMock: any;
let routerMock: any;
let dialogMock: any;
let moodServiceMock: any;
let screenSizeServiceMock: any;
let dialogRefMock: Partial<MatDialogRef<EditProfileModalComponent, any>>;

let authService: jest.Mocked<AuthService>;
let router: jest.Mocked<Router>;
let matDialog: jest.Mocked<MatDialog>;
let screenSizeService: jest.Mocked<ScreenSizeService>;
let spotifyService: jest.Mocked<SpotifyService>;
let providerService: jest.Mocked<ProviderService>;
let moodService: jest.Mocked<MoodService>;

beforeEach(async () => {
const dialogRefMock: Partial<MatDialogRef<EditProfileModalComponent, any>> = {
afterClosed: jest.fn().mockReturnValue(of(true)), // simulate afterClosed() returning a resolved value
close: jest.fn(), // mock the close method
componentInstance: {} as EditProfileModalComponent // mock the component instance if needed
};
authServiceMock = {
currentUser: jest.fn(() => of({ user: { user_metadata: { name: 'Test User', picture: 'test-pic.jpg' }}}))
};
spotifyServiceMock = {
getTopTracks: jest.fn(() => Promise.resolve([{ id: '1', text: 'Track 1', albumName: 'Album 1', imageUrl: '', secondaryText: '', previewUrl: '', spotifyUrl: '', explicit: false }])),
getTopArtists: jest.fn(() => Promise.resolve([{ id: '1', name: 'Artist 1', imageUrl: '', spotifyUrl: '' }])),
playTrackById: jest.fn()
};
providerServiceMock = {
getProviderName: jest.fn(() => 'spotify')
};
routerMock = { navigate: jest.fn() };
dialogMock = {
open: jest.fn().mockReturnValue(dialogRefMock)
};
moodServiceMock = { getCurrentMood: jest.fn(() => 'happy'), getComponentMoodClasses: jest.fn(() => ({})) };
screenSizeServiceMock = { screenSize$: of('large') };
authService = authServiceMock();
router = routerMock();
matDialog = matDialogMock();
screenSizeService = screenSizeServiceMock();
spotifyService = spotifyServiceMock();
providerService = providerServiceMock();
moodService = moodServiceMock();

await TestBed.configureTestingModule({
imports: [ProfileComponent],
providers: [
{ provide: AuthService, useValue: authServiceMock },
{ provide: SpotifyService, useValue: spotifyServiceMock },
{ provide: ProviderService, useValue: providerServiceMock },
{ provide: Router, useValue: routerMock },
{ provide: MatDialog, useValue: dialogMock },
{ provide: MoodService, useValue: moodServiceMock },
{ provide: ScreenSizeService, useValue: screenSizeServiceMock }
{ provide: AuthService, useValue: authService },
{ provide: Router, useValue: router },
{ provide: MatDialog, useValue: matDialog },
{ provide: ScreenSizeService, useValue: screenSizeService },
{ provide: SpotifyService, useValue: spotifyService },
{ provide: ProviderService, useValue: providerService },
{ provide: MoodService, useValue: moodService },
]
}).compileComponents();
});

beforeEach(() => {
fixture = TestBed.createComponent(ProfileComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create the component', () => {
it('should create', () => {
expect(component).toBeTruthy();
});

it('should set initial mood and classes from MoodService', () => {
expect(moodServiceMock.getCurrentMood).toHaveBeenCalled();
expect(component.currentMood).toBe('happy');
expect(component.moodComponentClasses).toEqual({});
});

it('should get the provider name and user info on AfterViewInit', () => {
it('should fetch user data on ngAfterViewInit if provider is Spotify', () => {
component.ngAfterViewInit();

expect(providerServiceMock.getProviderName).toHaveBeenCalled();
expect(authServiceMock.currentUser).toHaveBeenCalled();
expect(component.username).toBe('Test User');
expect(component.imgpath).toBe('test-pic.jpg');
});

it('should load top tracks and top artists on AfterViewInit', async () => {
await component.ngAfterViewInit();

expect(spotifyServiceMock.getTopTracks).toHaveBeenCalled();
expect(spotifyServiceMock.getTopArtists).toHaveBeenCalled();
expect(component.topTracks.length).toBe(1);
expect(component.topArtists.length).toBe(1);
});

it('should update screen size on subscription in ngOnInit', () => {
component.ngOnInit();

expect(screenSizeServiceMock.screenSize$).toBeTruthy();
expect(component.screenSize).toBe('large');
expect(authService.currentUser).toHaveBeenCalled();
expect(component.username).toEqual('mockname');
expect(component.imgpath).toEqual('path/to/picture');
expect(spotifyService.getTopTracks).toHaveBeenCalled();
expect(spotifyService.getTopArtists).toHaveBeenCalled();
});

it('should open the edit profile dialog when openDialog is called', () => {
component['dialog'] = {
open: jest.fn().mockReturnValue({
afterClosed: jest.fn().mockReturnValue(of({})), // or another observable if required
}),
} as unknown as MatDialog;
component.openDialog();

expect(component['dialog'].open).toHaveBeenCalled();
});

it('should save image path from localStorage if present', () => {
localStorage.setItem('path', 'new-path.jpg');
component.save();

expect(component.imgpath).toBe('new-path.jpg');
});

it('should refresh user data if provider is Spotify', () => {
providerServiceMock.getProviderName.mockResolvedValue('spotify');
component.refresh();

expect(providerServiceMock.getProviderName).toHaveBeenCalled();
expect(authServiceMock.currentUser).toHaveBeenCalled();
expect(component.username).toBe('Test User');
});

it('should navigate to settings page when settings is called', () => {
it('should navigate to /settings when settings is called', () => {
component.settings();

expect(routerMock.navigate).toHaveBeenCalledWith(['/settings']);
expect(router.navigate).toHaveBeenCalledWith(['/settings']);
});

it('should call SpotifyService to play a track when playTrack is called', () => {
component.playTrack('1');

expect(spotifyServiceMock.playTrackById).toHaveBeenCalledWith('1');
it('should play the track by id', () => {
const trackId = '1';
component.playTrack(trackId);
expect(spotifyService.playTrackById).toHaveBeenCalledWith(trackId);
});

it('should set the username if provider is spotify', (done) => {
// Arrange
const mockResponse = {
user: {
user_metadata: {
username: 'test_username'
}
}
};

jest.spyOn(providerServiceMock, 'getProviderName').mockReturnValue('spotify');
jest.spyOn(authServiceMock, 'currentUser').mockReturnValue(of(mockResponse)); // Mock the Observable response

// Act
component.refresh();

// Assert
authServiceMock.currentUser().subscribe(() => {
expect(component.username).toBe('test_username');
done(); // Make sure the async test completes
});
it('should subscribe to screenSize on ngOnInit', () => {
component.ngOnInit();
expect(component.screenSize).toBe('large');
});
/*
it('should not set the username if provider is not spotify', () => {
// Arrange
providerServiceMock.getProviderName.mockImplementation(() => 'pootify');

// Act
it('should update username on refresh if provider is Spotify', fakeAsync(() => {
providerService.getProviderName.mockReturnValue('spotify');
component.refresh();
// Assert
//expect(authServiceMock.currentUser).not.toHaveBeenCalled(); // currentUser() shouldn't be called
expect(component.username).toBeUndefined(); // Username shouldn't be set
});*/
tick();
expect(authService.currentUser).toHaveBeenCalled();
expect(component.username).toEqual('Test User');
}));
});
5 changes: 4 additions & 1 deletion Frontend/src/app/views/homes/homes.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { HomesComponent } from './homes.component';
import { provideHttpClient } from '@angular/common/http';

describe('HomesComponent', () => {
let component: HomesComponent;
let fixture: ComponentFixture<HomesComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HomesComponent]
imports: [HomesComponent],
providers: [
provideHttpClient()]
})
.compileComponents();

Expand Down

0 comments on commit fc60df3

Please sign in to comment.