|
| 1 | +import { TestBed } from '@angular/core/testing'; |
| 2 | +import { provideMockActions } from '@ngrx/effects/testing'; |
| 3 | +import { Action } from '@ngrx/store'; |
| 4 | +import { Observable, of, throwError } from 'rxjs'; |
| 5 | +import { UsersService } from '../services/users.service'; |
| 6 | +import { UserActionTypes } from './user.actions'; |
| 7 | +import { UserEffects } from './user.effects'; |
| 8 | +import { HttpClientTestingModule } from '@angular/common/http/testing'; |
| 9 | +import { ToastrModule, ToastrService } from 'ngx-toastr'; |
| 10 | + |
| 11 | +describe('UserEffects', () => { |
| 12 | + let actions$: Observable<Action>; |
| 13 | + let effects: UserEffects; |
| 14 | + let service: UsersService; |
| 15 | + let toastrService; |
| 16 | + const user = { id: 'id', name: 'name', email: 'email' }; |
| 17 | + |
| 18 | + beforeEach(() => { |
| 19 | + TestBed.configureTestingModule({ |
| 20 | + providers: [UserEffects, provideMockActions(() => actions$)], |
| 21 | + imports: [HttpClientTestingModule, ToastrModule.forRoot()], |
| 22 | + declarations: [], |
| 23 | + }); |
| 24 | + effects = TestBed.inject(UserEffects); |
| 25 | + service = TestBed.inject(UsersService); |
| 26 | + toastrService = TestBed.inject(ToastrService); |
| 27 | + }); |
| 28 | + |
| 29 | + it('should be created', async () => { |
| 30 | + expect(effects).toBeTruthy(); |
| 31 | + }); |
| 32 | + |
| 33 | + it('should return a list of users when the action LOAD_USERS is called', async () => { |
| 34 | + actions$ = of({ type: UserActionTypes.LOAD_USERS }); |
| 35 | + const serviceSpy = spyOn(service, 'loadUsers'); |
| 36 | + serviceSpy.and.returnValue(of(user)); |
| 37 | + |
| 38 | + effects.loadUsers$.subscribe((action) => { |
| 39 | + expect(action.type).toEqual(UserActionTypes.LOAD_USERS_SUCCESS); |
| 40 | + }); |
| 41 | + }); |
| 42 | + |
| 43 | + it('should return an error when the action LOAD_USERS call fails', async () => { |
| 44 | + actions$ = of({ type: UserActionTypes.LOAD_USERS }); |
| 45 | + const serviceSpy = spyOn(service, 'loadUsers'); |
| 46 | + serviceSpy.and.returnValue(throwError({ error: { message: 'fail!' } })); |
| 47 | + spyOn(toastrService, 'error'); |
| 48 | + |
| 49 | + effects.loadUsers$.subscribe((action) => { |
| 50 | + expect(toastrService.error).toHaveBeenCalled(); |
| 51 | + expect(action.type).toEqual(UserActionTypes.LOAD_USERS_FAIL); |
| 52 | + }); |
| 53 | + }); |
| 54 | +}); |
0 commit comments