juice-shop

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

6
import { TranslateModule, TranslateService } from '@ngx-translate/core'
7
import { HttpClientTestingModule } from '@angular/common/http/testing'
8
import { MatCardModule } from '@angular/material/card'
9
import { MatFormFieldModule } from '@angular/material/form-field'
10
import { type ComponentFixture, fakeAsync, TestBed, waitForAsync } from '@angular/core/testing'
11
import { MatInputModule } from '@angular/material/input'
12
import { ReactiveFormsModule } from '@angular/forms'
13
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
14

15
import { of, throwError } from 'rxjs'
16
import { MatTableModule } from '@angular/material/table'
17
import { MatExpansionModule } from '@angular/material/expansion'
18
import { MatDividerModule } from '@angular/material/divider'
19
import { MatRadioModule } from '@angular/material/radio'
20
import { PaymentService } from '../Services/payment.service'
21
import { MatDialogModule } from '@angular/material/dialog'
22
import { PaymentMethodComponent } from './payment-method.component'
23
import { EventEmitter } from '@angular/core'
24
import { MatSnackBar } from '@angular/material/snack-bar'
25

26
describe('PaymentMethodComponent', () => {
27
  let component: PaymentMethodComponent
28
  let fixture: ComponentFixture<PaymentMethodComponent>
29
  let paymentService
30
  let translateService
31
  let snackBar: any
32

33
  beforeEach(waitForAsync(() => {
34
    paymentService = jasmine.createSpyObj('BasketService', ['save', 'get', 'del'])
35
    paymentService.save.and.returnValue(of([]))
36
    paymentService.get.and.returnValue(of([]))
37
    paymentService.del.and.returnValue(of([]))
38
    translateService = jasmine.createSpyObj('TranslateService', ['get'])
39
    translateService.get.and.returnValue(of({}))
40
    translateService.onLangChange = new EventEmitter()
41
    translateService.onTranslationChange = new EventEmitter()
42
    translateService.onDefaultLangChange = new EventEmitter()
43
    snackBar = jasmine.createSpyObj('MatSnackBar', ['open'])
44

45
    TestBed.configureTestingModule({
46
      imports: [
47
        TranslateModule.forRoot(),
48
        HttpClientTestingModule,
49
        ReactiveFormsModule,
50

51
        BrowserAnimationsModule,
52
        MatCardModule,
53
        MatTableModule,
54
        MatFormFieldModule,
55
        MatInputModule,
56
        MatExpansionModule,
57
        MatDividerModule,
58
        MatRadioModule,
59
        MatDialogModule
60
      ],
61
      declarations: [PaymentMethodComponent],
62
      providers: [
63
        { provide: PaymentService, useValue: paymentService },
64
        { provide: TranslateService, useValue: translateService },
65
        { provide: MatSnackBar, useValue: snackBar }
66
      ]
67
    })
68
      .compileComponents()
69
  }))
70

71
  beforeEach(() => {
72
    fixture = TestBed.createComponent(PaymentMethodComponent)
73
    component = fixture.componentInstance
74
    fixture.detectChanges()
75
  })
76

77
  it('should create', () => {
78
    expect(component).toBeTruthy()
79
  })
80

81
  it('should hold cards returned by backend API', () => {
82
    paymentService.get.and.returnValue(of([{ cardNum: '************1231' }, { cardNum: '************6454' }]))
83
    component.load()
84
    expect(component.storedCards.length).toBe(2)
85
    expect(component.storedCards[0].cardNum).toBe('************1231')
86
    expect(component.storedCards[1].cardNum).toBe('************6454')
87
  })
88

89
  it('should hold no cards on error in backend API', fakeAsync(() => {
90
    paymentService.get.and.returnValue(throwError('Error'))
91
    component.load()
92
    expect(component.storedCards.length).toBe(0)
93
  }))
94

95
  it('should hold no cards when none are returned by backend API', () => {
96
    paymentService.get.and.returnValue(of([]))
97
    component.load()
98
    expect(component.storedCards).toEqual([])
99
  })
100

101
  it('should log error while getting Cards from backend API directly to browser console', fakeAsync(() => {
102
    paymentService.get.and.returnValue(throwError('Error'))
103
    console.log = jasmine.createSpy('log')
104
    component.load()
105
    expect(console.log).toHaveBeenCalledWith('Error')
106
  }))
107

108
  it('should reinitizalise new payment method form by calling resetForm', () => {
109
    component.nameControl.setValue('jim')
110
    component.numberControl.setValue(1234567887654321)
111
    component.monthControl.setValue(12)
112
    component.yearControl.setValue(2085)
113
    component.resetForm()
114
    expect(component.nameControl.value).toBe('')
115
    expect(component.nameControl.pristine).toBe(true)
116
    expect(component.nameControl.untouched).toBe(true)
117
    expect(component.numberControl.value).toBe('')
118
    expect(component.numberControl.pristine).toBe(true)
119
    expect(component.numberControl.untouched).toBe(true)
120
    expect(component.monthControl.value).toBe('')
121
    expect(component.monthControl.pristine).toBe(true)
122
    expect(component.monthControl.untouched).toBe(true)
123
    expect(component.yearControl.value).toBe('')
124
    expect(component.yearControl.pristine).toBe(true)
125
    expect(component.yearControl.untouched).toBe(true)
126
  })
127

128
  it('should be compulsory to provide name', () => {
129
    component.nameControl.setValue('')
130
    expect(component.nameControl.valid).toBeFalsy()
131
  })
132

133
  it('should be compulsory to provide card number', () => {
134
    component.numberControl.setValue('')
135
    expect(component.numberControl.valid).toBeFalsy()
136
  })
137

138
  it('should be compulsory to provide month', () => {
139
    component.monthControl.setValue('')
140
    expect(component.monthControl.valid).toBeFalsy()
141
  })
142

143
  it('should be compulsory to provide year', () => {
144
    component.yearControl.setValue('')
145
    expect(component.yearControl.valid).toBeFalsy()
146
  })
147

148
  it('card number should be in the range [1000000000000000, 9999999999999999]', () => {
149
    component.numberControl.setValue(1111110)
150
    expect(component.numberControl.valid).toBeFalsy()
151
    // eslint-disable-next-line @typescript-eslint/no-loss-of-precision
152
    component.numberControl.setValue(99999999999999999)
153
    expect(component.numberControl.valid).toBeFalsy()
154
    // eslint-disable-next-line @typescript-eslint/no-loss-of-precision
155
    component.numberControl.setValue(9999999999999999)
156
    expect(component.numberControl.valid).toBe(true)
157
    component.numberControl.setValue(1234567887654321)
158
    expect(component.numberControl.valid).toBe(true)
159
  })
160

161
  it('should reset the form on saving card and show confirmation', () => {
162
    paymentService.get.and.returnValue(of([]))
163
    paymentService.save.and.returnValue(of({ cardNum: '1234' }))
164
    translateService.get.and.returnValue(of('CREDIT_CARD_SAVED'))
165
    spyOn(component, 'resetForm')
166
    spyOn(component, 'load')
167
    component.save()
168
    expect(translateService.get).toHaveBeenCalledWith('CREDIT_CARD_SAVED', { cardnumber: '1234' })
169
    expect(component.load).toHaveBeenCalled()
170
    expect(component.resetForm).toHaveBeenCalled()
171
  })
172

173
  it('should clear the form and display error if saving card fails', fakeAsync(() => {
174
    paymentService.save.and.returnValue(throwError({ error: 'Error' }))
175
    spyOn(component, 'resetForm')
176
    component.save()
177
    expect(snackBar.open).toHaveBeenCalled()
178
    expect(component.resetForm).toHaveBeenCalled()
179
  }))
180
})
181

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

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

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

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