Skip to content

Commit

Permalink
Merge pull request #72 from danieljancar/52-features-components-tests
Browse files Browse the repository at this point in the history
feat: add spec tests to frontend
  • Loading branch information
danieljancar authored Aug 15, 2024
2 parents e4ffa89 + 1b5bb54 commit f9da174
Show file tree
Hide file tree
Showing 11 changed files with 466 additions and 22 deletions.
28 changes: 15 additions & 13 deletions apps/frontend/src/app/app.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
import { TestBed } from '@angular/core/testing'
import { AppComponent } from './app.component'
import { NxWelcomeComponent } from './nx-welcome.component'
import { RouterModule } from '@angular/router'
import { AuthService } from './core/auth.service'
import { HttpClient } from '@angular/common/http'

describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent, NxWelcomeComponent, RouterModule.forRoot([])],
imports: [AppComponent, RouterModule.forRoot([])],
providers: [
{
provide: AuthService,
useValue: {},
},
{
provide: HttpClient,
useValue: {},
},
],
}).compileComponents()
})

it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent)
fixture.detectChanges()
const compiled = fixture.nativeElement as HTMLElement
expect(compiled.querySelector('h1')?.textContent).toContain(
'Welcome frontend',
)
})

it(`should have as title 'frontend'`, () => {
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent)
const app = fixture.componentInstance
expect(app.title).toEqual('frontend')
expect(app).toBeTruthy()
})
})
28 changes: 23 additions & 5 deletions apps/frontend/src/app/features/home/home.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,29 @@ describe('HomeComponent', () => {
expect(component).toBeTruthy()
})

test('should search vote', inject([Router], (mockRouter: Router) => {
const spyRouter = spyOn(mockRouter, 'navigate').and.stub()

test('searchVote', () => {
const router = TestBed.inject(Router)
const navigateSpy = jest.spyOn(router, 'navigate')
component.voteId.setValue('123')
component.searchVote()
expect(spyRouter.calls.first().args[0]).toContain('voting' && '123')
}))
expect(navigateSpy).toHaveBeenCalledWith(['/voting', '123'])
})

test('createVote', () => {
const router = TestBed.inject(Router)
const navigateSpy = jest.spyOn(router, 'navigate')
component.createVote()
expect(navigateSpy).toHaveBeenCalledWith(['/voting', 'create'])
})

test('pasteVoteId', async () => {
const clipboard = {
readText: jest.fn().mockResolvedValue('123'),
}
Object.defineProperty(navigator, 'clipboard', {
value: clipboard,
})
await component.pasteVoteId()
expect(component.voteId.value).toBe('123')
})
})
19 changes: 18 additions & 1 deletion apps/frontend/src/app/features/login/login.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,38 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { LoginComponent } from './login.component'
import { AuthService } from '../../core/auth.service'
import { ChangeDetectorRef } from '@angular/core'
import { ReactiveFormsModule } from '@angular/forms'

describe('LoginComponent', () => {
let component: LoginComponent
let fixture: ComponentFixture<LoginComponent>
let authService: AuthService

beforeEach(async () => {
const mockAuthService = {
loginUsingPrivateKey: jest.fn().mockResolvedValue(true),
}
await TestBed.configureTestingModule({
imports: [LoginComponent],
imports: [ReactiveFormsModule, LoginComponent],
providers: [
{ provide: AuthService, useValue: mockAuthService },
ChangeDetectorRef,
],
}).compileComponents()

fixture = TestBed.createComponent(LoginComponent)
component = fixture.componentInstance
authService = TestBed.inject(AuthService)
fixture.detectChanges()
})

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

it('should call loginUsingPrivateKey on authService', async () => {
await component.logInUsingPrivateKey()
expect(authService.loginUsingPrivateKey).toHaveBeenCalled()
})
})
21 changes: 21 additions & 0 deletions apps/frontend/src/app/features/register/register.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,42 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { RegisterComponent } from './register.component'
import { AuthService } from '../../core/auth.service'
import { ChangeDetectorRef } from '@angular/core'

describe('RegisterComponent', () => {
let component: RegisterComponent
let fixture: ComponentFixture<RegisterComponent>
let authService: AuthService

beforeEach(async () => {
const mockAuthService = {
generateKeypair: jest.fn().mockReturnValue({
publicKey: jest.fn().mockReturnValue('publicKey'),
secret: jest.fn().mockReturnValue,
}),
fundAccount: jest.fn().mockResolvedValue(true),
}

await TestBed.configureTestingModule({
imports: [RegisterComponent],
providers: [
{ provide: AuthService, useValue: mockAuthService },
ChangeDetectorRef,
],
}).compileComponents()

fixture = TestBed.createComponent(RegisterComponent)
component = fixture.componentInstance
authService = TestBed.inject(AuthService)
fixture.detectChanges()
})

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

it('should generate keypair', () => {
component.generateKeypair()
expect(authService.generateKeypair).toHaveBeenCalled()
})
})
123 changes: 120 additions & 3 deletions apps/frontend/src/app/features/voting/cast/cast.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,139 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'

import { ReactiveFormsModule } from '@angular/forms'
import { Router } from '@angular/router'
import { CastComponent } from './cast.component'
import { VoteConfigService } from '../../../core/vote-transaction.service'
import { CastVoteService } from '../../../core/stellar/castVote.service'
import { ConfirmReloadService } from '../../../shared/services/confirm-reload/confirm-reload.service'
import { GetVoteOptionService } from '../../../core/stellar/getVoteOption.service'
import { LoadingComponent } from '../../../shared/feedback/loading/loading.component'
import { ErrorComponent } from '../../../shared/feedback/error/error.component'

describe('CastComponent', () => {
let component: CastComponent
let fixture: ComponentFixture<CastComponent>
let voteConfigService: VoteConfigService
let router: Router
let confirmReloadService: ConfirmReloadService

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CastComponent],
imports: [
CastComponent,
LoadingComponent,
ErrorComponent,
ReactiveFormsModule,
],
providers: [
{
provide: VoteConfigService,
useValue: {
getBaseVoteConfig: jest.fn(),
},
},
{
provide: CastVoteService,
useValue: {
castVote: jest.fn(),
},
},
{
provide: ConfirmReloadService,
useValue: {
confirmReload: jest.fn().mockReturnValue(true),
},
},
{
provide: GetVoteOptionService,
useValue: {},
},
{
provide: Router,
useValue: {
navigate: jest.fn(),
},
},
],
}).compileComponents()

fixture = TestBed.createComponent(CastComponent)
component = fixture.componentInstance
fixture.detectChanges()
voteConfigService = TestBed.inject(VoteConfigService)
router = TestBed.inject(Router)
confirmReloadService = TestBed.inject(ConfirmReloadService)
})

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

it('should initialize the form with required fields', () => {
expect(component.voteForm.contains('selectedOption')).toBeTruthy()
expect(component.voteForm.get('selectedOption')?.valid).toBeFalsy()
})

it('should handle input changes and remove duplicates', async () => {
const options = ['Option1', 'Option2', 'Option1']
const data = ['Data1', 'Data2', 'Data1']

component.optionsArr = options
component.dataArr = data
await component.ngOnChanges({
optionsArr: {
currentValue: options,
previousValue: [],
firstChange: true,
isFirstChange(): boolean {
return true
},
},
dataArr: {
currentValue: data,
previousValue: [],
firstChange: true,
isFirstChange(): boolean {
return true
},
},
})

expect(component.optionsArr).toEqual(['Option1', 'Option2'])
expect(component.dataArr).toEqual(['Data1', 'Data2'])
})

it('should handle errors when fetching vote configuration', async () => {
jest
.spyOn(voteConfigService, 'getBaseVoteConfig')
.mockRejectedValueOnce(new Error('Fetch error'))

await component.ngOnChanges({})

expect(component.hasError).toBeTruthy()
expect(component.errorMessage).toBe('Failed to load vote configuration.')
})

it('should navigate to results view if form is clean', () => {
component.voteId = '123'
component.viewResults()

expect(router.navigate).toHaveBeenCalledWith(['/voting/r', '123'])
})

it('should not navigate to results view if form is dirty and confirm is false', () => {
jest.spyOn(confirmReloadService, 'confirmReload').mockReturnValueOnce(false)
component.voteForm.markAsDirty()
component.voteId = '123'
component.viewResults()

expect(router.navigate).not.toHaveBeenCalled()
})

it('should reset error state on errorAction call', () => {
component.hasError = true
component.errorMessage = 'Some error'
component.errorAction()

expect(component.hasError).toBeFalsy()
expect(component.errorMessage).toBe('')
})
})
Loading

0 comments on commit f9da174

Please sign in to comment.