I have checked a lot of articles and answers but I don't seem to find the right way to mock HTTP Requests
for my methods. I want to test my frontend
application independently from the backend
. Here is the type of methods I have:
private getProfile() {
this.http
.get('go/profile/get', {withCredentials: true})
.subscribe((profile: Profile) => {
this.user.profile = profile;
this.updateLineMsgs();
});
}
Any suggestions ?
Usually i mock my Http requests with HttpClientTestingModule :
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
export class TestService {
constructor(private http: HttpClient) {}
}
describe('AppInterceptor', () => {
let service: TestService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
TestService
]
});
service = TestBed.inject(TestService);
httpMock = TestBed.inject(HttpTestingController);
});
//...
const httpRequest = httpMock.expectOne('any-url');
You can always create a mock method by your own and mock the response that you expect from the backend. In your example it could be
public static mockGetProfile(){
const response = JSON.parse(`
"name": "abc",
"active": true,
...all other json fields that you want
`);
let obs = new Observable((subscriber) => {
setTimeout(()=>{
subscriber.next(response);
subscriber.complete();
}, 3000);
});
return obs;
}
The above observable will complete after 3 seconds or what ever period you define, simulating in a way the response from a backend server which will need some time to be available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With