juice-shop

Форк
0
/
recycle.component.spec.ts 
221 строка · 9.2 Кб
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 { MatDatepickerModule } from '@angular/material/datepicker'
8
import { ConfigurationService } from '../Services/configuration.service'
9
import { UserService } from '../Services/user.service'
10
import { RecycleService } from '../Services/recycle.service'
11
import { HttpClientTestingModule } from '@angular/common/http/testing'
12
import { MatCardModule } from '@angular/material/card'
13
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
14
import { MatButtonModule } from '@angular/material/button'
15
import { MatInputModule } from '@angular/material/input'
16
import { type ComponentFixture, fakeAsync, TestBed, waitForAsync } from '@angular/core/testing'
17

18
import { RecycleComponent } from './recycle.component'
19
import { MatFormFieldModule } from '@angular/material/form-field'
20
import { ReactiveFormsModule } from '@angular/forms'
21
import { MatCheckboxModule } from '@angular/material/checkbox'
22
import { MatNativeDateModule } from '@angular/material/core'
23
import { of, throwError } from 'rxjs'
24
import { AddressComponent } from '../address/address.component'
25
import { RouterTestingModule } from '@angular/router/testing'
26
import { EventEmitter } from '@angular/core'
27
import { MatIconModule } from '@angular/material/icon'
28
import { MatTableModule } from '@angular/material/table'
29
import { MatToolbarModule } from '@angular/material/toolbar'
30
import { MatRadioModule } from '@angular/material/radio'
31
import { MatTooltipModule } from '@angular/material/tooltip'
32
import { MatDialogModule } from '@angular/material/dialog'
33
import { MatDividerModule } from '@angular/material/divider'
34
import { MatSnackBar } from '@angular/material/snack-bar'
35

36
describe('RecycleComponent', () => {
37
  let component: RecycleComponent
38
  let fixture: ComponentFixture<RecycleComponent>
39
  let recycleService: any
40
  let userService: any
41
  let configurationService: any
42
  let translateService
43
  let snackBar: any
44

45
  beforeEach(waitForAsync(() => {
46
    recycleService = jasmine.createSpyObj('RecycleService', ['save', 'find'])
47
    recycleService.save.and.returnValue(of({}))
48
    recycleService.find.and.returnValue(of([{}]))
49
    userService = jasmine.createSpyObj('UserService', ['whoAmI'])
50
    userService.whoAmI.and.returnValue(of({}))
51
    configurationService = jasmine.createSpyObj('ConfigurationService', ['getApplicationConfiguration'])
52
    configurationService.getApplicationConfiguration.and.returnValue(of({}))
53
    translateService = jasmine.createSpyObj('TranslateService', ['get'])
54
    translateService.get.and.returnValue(of({}))
55
    translateService.onLangChange = new EventEmitter()
56
    translateService.onTranslationChange = new EventEmitter()
57
    translateService.onDefaultLangChange = new EventEmitter()
58
    snackBar = jasmine.createSpyObj('MatSnackBar', ['open'])
59

60
    TestBed.configureTestingModule({
61
      imports: [
62
        RouterTestingModule,
63
        TranslateModule.forRoot(),
64
        HttpClientTestingModule,
65
        BrowserAnimationsModule,
66
        ReactiveFormsModule,
67
        MatFormFieldModule,
68
        MatInputModule,
69
        MatButtonModule,
70
        MatCardModule,
71
        MatCheckboxModule,
72
        MatDatepickerModule,
73
        MatNativeDateModule,
74
        MatIconModule,
75
        MatToolbarModule,
76
        MatTableModule,
77
        MatRadioModule,
78
        MatTooltipModule,
79
        MatDialogModule,
80
        MatDividerModule
81
      ],
82
      declarations: [RecycleComponent, AddressComponent],
83
      providers: [
84
        { provide: RecycleService, useValue: recycleService },
85
        { provide: UserService, useValue: userService },
86
        { provide: ConfigurationService, useValue: configurationService },
87
        { provide: TranslateService, useValue: translateService },
88
        { provide: MatSnackBar, useValue: snackBar }
89
      ]
90
    })
91
      .compileComponents()
92
  }))
93

94
  beforeEach(() => {
95
    fixture = TestBed.createComponent(RecycleComponent)
96
    component = fixture.componentInstance
97
    fixture.detectChanges()
98
  })
99

100
  it('should create', () => {
101
    expect(component).toBeTruthy()
102
  })
103

104
  it('should reset the form by calling resetForm', () => {
105
    component.addressId = '1'
106
    component.recycleQuantityControl.setValue('100')
107
    component.pickUpDateControl.setValue('10/7/2018')
108
    component.pickup.setValue(true)
109
    component.resetForm()
110
    expect(component.addressId).toBeUndefined()
111
    expect(component.recycleQuantityControl.value).toBe('')
112
    expect(component.recycleQuantityControl.untouched).toBe(true)
113
    expect(component.recycleQuantityControl.pristine).toBe(true)
114
    expect(component.pickUpDateControl.value).toBe('')
115
    expect(component.pickUpDateControl.untouched).toBe(true)
116
    expect(component.pickUpDateControl.pristine).toBe(true)
117
    expect(component.pickup.value).toBe(false)
118
  })
119

120
  it('should hold the user id of the currently logged in user', () => {
121
    userService.whoAmI.and.returnValue(of({ id: 42 }))
122
    component.ngOnInit()
123
    expect(component.recycle.UserId).toBe(42)
124
  })
125

126
  it('should hold no email if current user is not logged in', () => {
127
    userService.whoAmI.and.returnValue(of({}))
128
    component.ngOnInit()
129
    expect(component.userEmail).toBeUndefined()
130
  })
131

132
  it('should hold the user email of the currently logged in user', () => {
133
    userService.whoAmI.and.returnValue(of({ email: 'x@x.xx' }))
134
    component.ngOnInit()
135
    expect(component.userEmail).toBe('x@x.xx')
136
  })
137

138
  it('should display pickup message and reset recycle form on saving', () => {
139
    recycleService.save.and.returnValue(of({}))
140
    userService.whoAmI.and.returnValue(of({}))
141
    translateService.get.and.returnValue(of('CONFIRM_RECYCLING_BOX'))
142
    spyOn(component, 'initRecycle')
143
    spyOn(component.addressComponent, 'load')
144
    component.addressId = '1'
145
    component.recycleQuantityControl.setValue(100)
146
    component.pickup.setValue(false)
147
    const recycle = { UserId: undefined, AddressId: '1', quantity: 100 }
148
    component.save()
149
    expect(recycleService.save.calls.count()).toBe(1)
150
    expect(recycleService.save.calls.argsFor(0)[0]).toEqual(recycle)
151
    expect(component.initRecycle).toHaveBeenCalled()
152
    expect(component.addressComponent.load).toHaveBeenCalled()
153
    expect(translateService.get).toHaveBeenCalledWith('CONFIRM_RECYCLING_BOX')
154
  })
155

156
  it('should display pickup message and reset recycle form on saving when pickup is selected', () => {
157
    recycleService.save.and.returnValue(of({ isPickup: true, pickupDate: '10/7/2018' }))
158
    userService.whoAmI.and.returnValue(of({}))
159
    translateService.get.and.returnValue(of('CONFIRM_RECYCLING_PICKUP'))
160
    spyOn(component, 'initRecycle')
161
    spyOn(component.addressComponent, 'load')
162
    component.addressId = '1'
163
    component.recycleQuantityControl.setValue(100)
164
    component.pickup.setValue(true)
165
    component.pickUpDateControl.setValue('10/7/2018')
166
    const recycle = { isPickUp: true, date: '10/7/2018', UserId: undefined, AddressId: '1', quantity: 100 }
167
    component.save()
168
    expect(recycleService.save.calls.count()).toBe(1)
169
    expect(recycleService.save.calls.argsFor(0)[0]).toEqual(recycle)
170
    expect(component.initRecycle).toHaveBeenCalled()
171
    expect(component.addressComponent.load).toHaveBeenCalled()
172
    expect(translateService.get).toHaveBeenCalledWith('CONFIRM_RECYCLING_PICKUP', { pickupdate: '10/7/2018' })
173
  })
174

175
  it('should hold existing recycles', () => {
176
    recycleService.find.and.returnValue(of([{ quantity: 1 }, { quantity: 2 }]))
177
    component.ngOnInit()
178
    expect(component.recycles.length).toBe(2)
179
    expect(component.recycles[0].quantity).toBe(1)
180
    expect(component.recycles[1].quantity).toBe(2)
181
  })
182

183
  it('should hold nothing when no recycles exists', () => {
184
    recycleService.find.and.returnValue(of([]))
185
    component.ngOnInit()
186
    expect(component.recycles.length).toBe(0)
187
  })
188

189
  it('should hold nothing on error from backend API', () => {
190
    recycleService.find.and.returnValue(throwError('Error'))
191
    console.log = jasmine.createSpy('log')
192
    component.ngOnInit()
193
    expect(console.log).toHaveBeenCalledWith('Error')
194
  })
195

196
  it('should log the error on retrieving the user', fakeAsync(() => {
197
    userService.whoAmI.and.returnValue(throwError('Error'))
198
    console.log = jasmine.createSpy('log')
199
    component.ngOnInit()
200
    expect(console.log).toHaveBeenCalledWith('Error')
201
  }))
202

203
  it('should use a configured product image on top of page', () => {
204
    configurationService.getApplicationConfiguration.and.returnValue(of({ application: { recyclePage: { topProductImage: 'top.png' } } }))
205
    component.ngOnInit()
206
    expect(component.topImage).toEqual('assets/public/images/products/top.png')
207
  })
208

209
  it('should use a configured product image on bottom of page', () => {
210
    configurationService.getApplicationConfiguration.and.returnValue(of({ application: { recyclePage: { topProductImage: 'bottom.png' } } }))
211
    component.ngOnInit()
212
    expect(component.topImage).toEqual('assets/public/images/products/bottom.png')
213
  })
214

215
  it('should show broken top and bottom image on error retrieving configuration', fakeAsync(() => {
216
    configurationService.getApplicationConfiguration.and.returnValue(throwError('Error'))
217
    component.ngOnInit()
218
    expect(component.topImage).toBeUndefined()
219
    expect(component.bottomImage).toBeUndefined()
220
  }))
221
})
222

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

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

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

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