Newer
Older
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { User } from '../models/user.model';
import { UserService } from './user.service';
describe('UserService', () => {
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
let service: UserService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
});
service = TestBed.inject(UserService);
httpMock = TestBed.inject(HttpTestingController);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
describe('getUser', () => {
it('should get an user', () => {
// Gets post and checks values
service.getUser(1).then(user => {
expect(user.getUserId).toBe(1);
expect(user.getUsername).toBe("zorg");
}).catch(error => {
fail();
});
// Mocks and checks HTTP request
const req = httpMock.expectOne("api/user/1");
expect(req.request.method).toBe("GET");
req.flush({
data: [{
userId: 1,
username: "zorg",
email: "blob@planet.us",
password: "Hyttepine",
create_time: 1613552549000,
}]
});
});
it('should reject on invalid user', () => {
// Gets invalid post, should go to catch
service.getUser(2).then(user => {
fail();
}).catch(error => {});
// Mocks and checks HTTP request
const req = httpMock.expectOne("api/user/2");
expect(req.request.method).toBe("GET");
req.flush({
data: [{
userId: 0,
username: "zorg",
email: "blob@planet.us",
password: "Hyttepine",
}]
});
});
it('should reject on http error', () => {
// Gets HTTP error instead of post, should catch
service.getUser(2).then(user => {
fail();
}).catch(error => {});
// Mocks and checks HTTP request
const req = httpMock.expectOne("api/user/2");
expect(req.request.method).toBe("GET");
req.error(new ErrorEvent("400"));
});
});
describe('deleteUser', () => {
it('should delete user', () => {
// Deletes user with id = 2
service.deleteUser(2)
.then(data => {})
.catch(error => {
fail();
});
// Mocks and checks HTTP request
const req = httpMock.expectOne("api/user/2");
expect(req.request.method).toBe("DELETE");
req.flush({
data: []
});
});
it('should reject on http error', () => {
// Deletes user with id = 2, but should catch HTTP error
service.deleteUser(2).then(data => {
fail();
}).catch(error => {});
// Mocks and checks HTTP request
const req = httpMock.expectOne("api/user/2");
expect(req.request.method).toBe("DELETE");
req.error(new ErrorEvent("400"));
});
});