@@ -2,18 +2,76 @@ import { TestBed } from '@angular/core/testing';
2
2
3
3
import { UsersService } from './users.service' ;
4
4
import { HttpClientTestingModule } from '@angular/common/http/testing' ;
5
+ import { HttpClient , HttpParams } from '@angular/common/http' ;
6
+ import { of , Observable } from 'rxjs' ;
7
+ import { environment } from 'src/environments/environment' ;
8
+ import { User } from '../models/user.model' ;
5
9
6
10
describe ( 'UsersService' , ( ) => {
7
11
let service : UsersService ;
12
+ let httpClientSpy : jasmine . SpyObj < HttpClient > ;
8
13
9
14
beforeEach ( ( ) => {
15
+ //create http spy
16
+ const httpSpy = jasmine . createSpyObj ( 'HttpClient' , [ 'get' , 'post' ] ) ;
17
+
10
18
TestBed . configureTestingModule ( {
11
19
imports : [ HttpClientTestingModule ] ,
20
+ providers : [ { provide : HttpClient , useValue : httpSpy } ] ,
12
21
} ) ;
13
22
service = TestBed . inject ( UsersService ) ;
23
+ httpClientSpy = TestBed . inject ( HttpClient ) as jasmine . SpyObj < HttpClient > ;
14
24
} ) ;
15
25
16
26
it ( 'should be created' , ( ) => {
17
27
expect ( service ) . toBeTruthy ( ) ;
18
28
} ) ;
29
+
30
+ describe ( 'getUsers' , ( ) => {
31
+ it ( 'should send a GET request to the correct URL without pagination parameters' , ( ) => {
32
+ httpClientSpy . get . and . returnValue ( of ( [ ] ) ) ;
33
+
34
+ service . getUsers ( ) . subscribe ( ( ) => { } ) ;
35
+ expect ( httpClientSpy . get ) . toHaveBeenCalledWith (
36
+ environment . apiUrl + 'users' ,
37
+ {
38
+ params : new HttpParams ( ) ,
39
+ }
40
+ ) ;
41
+ } ) ;
42
+ // @Todo - need to write test case
43
+ xit ( 'should send a GET request to the correct URL with pagination parameters' , ( ) => {
44
+ const pageIndex = 2 ;
45
+ const pageSize = 10 ;
46
+ const params = new HttpParams ( ) . append ( 'page' , '3' ) . append ( 'limit' , '10' ) ;
47
+ httpClientSpy . get . and . returnValue ( of ( [ ] ) ) ;
48
+ service . getUsers ( pageIndex , pageSize ) . subscribe ( ( ) => { } ) ;
49
+ expect ( httpClientSpy . get ) . toHaveBeenCalledWith (
50
+ environment . apiUrl + 'users' ,
51
+ {
52
+ params,
53
+ }
54
+ ) ;
55
+ } ) ;
56
+ } ) ;
57
+
58
+ describe ( 'addUser' , ( ) => {
59
+ it ( 'should send a POST request to the correct URL with the provided user' , ( ) => {
60
+ const user : User = {
61
+ id : 1 ,
62
+ name : 'John Doe' ,
63
+ avatar : '' ,
64
+ status : false ,
65
+ email : '' ,
66
+ createdAt : '' ,
67
+ } ;
68
+ httpClientSpy . post . and . returnValue ( of ( user ) ) ;
69
+ const result = service . addUser ( user ) ;
70
+ expect ( httpClientSpy . post ) . toHaveBeenCalledWith (
71
+ environment . apiUrl + 'users' ,
72
+ user
73
+ ) ;
74
+ expect ( result ) . toBeInstanceOf ( Observable ) ;
75
+ } ) ;
76
+ } ) ;
19
77
} ) ;
0 commit comments