juice-shop

Форк
0
/
register.component.spec.ts 
191 строка · 7.6 Кб
1
/*
2
 * Copyright (c) 2014-2024 Bjoern Kimminich & the OWASP Juice Shop contributors.
3
 * SPDX-License-Identifier: MIT
4
 */
5

6
import { LoginComponent } from '../login/login.component'
7
import { SecurityAnswerService } from '../Services/security-answer.service'
8
import { UserService } from '../Services/user.service'
9
import { SecurityQuestionService } from '../Services/security-question.service'
10
import { HttpClientTestingModule } from '@angular/common/http/testing'
11
import { type ComponentFixture, fakeAsync, flush, TestBed, tick, waitForAsync } from '@angular/core/testing'
12
import { RegisterComponent } from './register.component'
13
import { ReactiveFormsModule } from '@angular/forms'
14
import { RouterTestingModule } from '@angular/router/testing'
15
import { Location } from '@angular/common'
16
import { TranslateModule } from '@ngx-translate/core'
17
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
18
import { MatButtonModule } from '@angular/material/button'
19
import { MatSelectModule } from '@angular/material/select'
20
import { MatInputModule } from '@angular/material/input'
21
import { MatFormFieldModule } from '@angular/material/form-field'
22
import { MatCardModule } from '@angular/material/card'
23
import { MatIconModule } from '@angular/material/icon'
24
import { of, throwError } from 'rxjs'
25
import { MatCheckboxModule } from '@angular/material/checkbox'
26
import { MatSnackBarModule } from '@angular/material/snack-bar'
27
import { MatTooltipModule } from '@angular/material/tooltip'
28
import { MatPasswordStrengthModule } from '@angular-material-extensions/password-strength'
29
import { MatSlideToggleModule } from '@angular/material/slide-toggle'
30

31
describe('RegisterComponent', () => {
32
  let component: RegisterComponent
33
  let fixture: ComponentFixture<RegisterComponent>
34
  let securityAnswerService: any
35
  let securityQuestionService: any
36
  let userService: any
37
  let location: Location
38

39
  beforeEach(waitForAsync(() => {
40
    securityAnswerService = jasmine.createSpyObj('SecurityAnswerService', ['save'])
41
    securityAnswerService.save.and.returnValue(of({}))
42
    securityQuestionService = jasmine.createSpyObj('SecurityQuestionService', ['find'])
43
    securityQuestionService.find.and.returnValue(of([{}]))
44
    userService = jasmine.createSpyObj('UserService', ['save'])
45
    userService.save.and.returnValue(of({}))
46
    TestBed.configureTestingModule({
47
      imports: [
48
        RouterTestingModule.withRoutes([
49
          { path: 'login', component: LoginComponent }
50
        ]),
51
        TranslateModule.forRoot(),
52
        MatPasswordStrengthModule.forRoot(),
53
        HttpClientTestingModule,
54
        ReactiveFormsModule,
55
        BrowserAnimationsModule,
56
        MatCardModule,
57
        MatFormFieldModule,
58
        MatCheckboxModule,
59
        MatInputModule,
60
        MatSelectModule,
61
        MatButtonModule,
62
        MatIconModule,
63
        MatSnackBarModule,
64
        MatTooltipModule,
65
        MatIconModule,
66
        MatSlideToggleModule
67
      ],
68
      declarations: [RegisterComponent, LoginComponent],
69
      providers: [
70
        { provide: SecurityAnswerService, useValue: securityAnswerService },
71
        { provide: SecurityQuestionService, useValue: securityQuestionService },
72
        { provide: UserService, useValue: userService }
73
      ]
74
    })
75
      .compileComponents()
76

77
    location = TestBed.inject(Location)
78
  }))
79

80
  beforeEach(() => {
81
    fixture = TestBed.createComponent(RegisterComponent)
82
    component = fixture.componentInstance
83
    fixture.detectChanges()
84
  })
85

86
  it('should create', () => {
87
    expect(component).toBeTruthy()
88
  })
89

90
  it('should be compulsory to provid email', () => {
91
    component.emailControl.setValue('')
92
    expect(component.emailControl.valid).toBeFalsy()
93
  })
94

95
  it('email field should be of proper format', () => {
96
    component.emailControl.setValue('email')
97
    expect(component.emailControl.valid).toBeFalsy()
98
    component.emailControl.setValue('x@x.xx')
99
    expect(component.emailControl.valid).toBe(true)
100
  })
101

102
  it('should be compulsory to provide password', () => {
103
    component.passwordControl.setValue('')
104
    expect(component.passwordControl.valid).toBeFalsy()
105
  })
106

107
  it('password should have at least five characters', () => {
108
    component.passwordControl.setValue('aaaa')
109
    expect(component.passwordControl.valid).toBeFalsy()
110
    component.passwordControl.setValue('aaaaa')
111
    expect(component.passwordControl.valid).toBe(true)
112
  })
113

114
  it('password should not be more than 20 characters', () => {
115
    let password: string = ''
116
    for (let i = 0; i < 41; i++) {
117
      password += 'a'
118
    }
119
    component.passwordControl.setValue(password)
120
    expect(component.passwordControl.valid).toBeFalsy()
121
    password = password.slice(1)
122
    component.passwordControl.setValue(password)
123
    expect(component.passwordControl.valid).toBe(true)
124
  })
125

126
  it('should be compulsory to repeat the password', () => {
127
    component.passwordControl.setValue('a')
128
    component.repeatPasswordControl.setValue('')
129
    expect(component.repeatPasswordControl.valid).toBeFalsy()
130
    component.repeatPasswordControl.setValue('a')
131
    expect(component.repeatPasswordControl.valid).toBe(true)
132
  })
133

134
  it('password and repeat password should be the same', () => {
135
    const password: string = 'aaaaa'
136
    const passwordRepeat: string = 'aaaaa'
137
    component.passwordControl.setValue(password)
138
    component.repeatPasswordControl.setValue('bbbbb')
139
    expect(component.repeatPasswordControl.valid).toBeFalsy()
140
    component.repeatPasswordControl.setValue(passwordRepeat)
141
    expect(component.repeatPasswordControl.valid).toBe(true)
142
  })
143

144
  it('redirects to login page after user registration', fakeAsync(() => {
145
    userService.save.and.returnValue(of({ id: 1, question: 'Wat is?' }))
146
    securityAnswerService.save.and.returnValue(of({}))
147
    component.securityQuestions = [{ id: 1, question: 'Wat is?' }]
148
    component.emailControl.setValue('x@x.xx')
149
    component.passwordControl.setValue('password')
150
    component.repeatPasswordControl.setValue('password')
151
    component.securityQuestionControl.setValue(1)
152
    component.securityAnswerControl.setValue('Answer')
153
    const user = { email: 'x@x.xx', password: 'password', passwordRepeat: 'password', securityQuestion: { id: 1, question: 'Wat is?' }, securityAnswer: 'Answer' }
154
    const securityAnswerObject = { UserId: 1, answer: 'Answer', SecurityQuestionId: 1 }
155
    component.save()
156
    tick()
157
    expect(userService.save.calls.argsFor(0)[0]).toEqual(user)
158
    expect(securityAnswerService.save.calls.argsFor(0)[0]).toEqual(securityAnswerObject)
159
    expect(location.path()).toBe('/login')
160
    fixture.destroy()
161
    flush()
162
  }))
163

164
  it('loading secret questions', () => {
165
    securityQuestionService.find.and.returnValue(of([{ id: 1, question: 'WTF?' }, { id: 2, question: 'WAT?' }]))
166
    component.ngOnInit()
167
    expect(component.securityQuestions.length).toBe(2)
168
    expect(component.securityQuestions[0].question).toBe('WTF?')
169
    expect(component.securityQuestions[1].question).toBe('WAT?')
170
  })
171

172
  it('should hold nothing when no secret questions exists', () => {
173
    securityQuestionService.find.and.returnValue(of(undefined))
174
    component.ngOnInit()
175
    expect(component.securityQuestions).toBeUndefined()
176
  })
177

178
  it('should log error from backend API on failing to get security questions', fakeAsync(() => {
179
    securityQuestionService.find.and.returnValue(throwError('Error'))
180
    console.log = jasmine.createSpy('log')
181
    component.ngOnInit()
182
    expect(console.log).toHaveBeenCalledWith('Error')
183
  }))
184

185
  it('should log error on saving user', fakeAsync(() => {
186
    userService.save.and.returnValue(throwError('Error'))
187
    console.log = jasmine.createSpy('log')
188
    component.save()
189
    expect(console.log).toHaveBeenCalledWith('Error')
190
  }))
191
})
192

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.