I have a pretty standard Angular application, which comes with the standard Jasmine + Karma frameworks for unit testing.
In my application I have several services which make use of the HttpClient class to query a back-end, and I obviously need to unit test all these services too.
I realized I need to mock the back-end with a local server, which answers to the HTTP queries with hard-coded JSON.
I found many different suggestions on-line, but they don't fit or are too complicated.
What I'd like to have:
- no additional code to be added to the original angular services
- no tricky solutions (like using HTTP Interceptors, etc.)
- no complicated proxy configuration, or definition of specific
npm runscripts - easy to write fake DB (e.g. hard-coded JSON file)
- since my real back-end exposes Restful APIs, with standard CRUD operations, I would like to avoid describing each single end-point in the fake back-end
- when I type
ng testthe fake back-end (with a different base URL) should be automatically used
Thanks,
Thomas
You can mock your backend by using the HttpTestingController This class allows you to test that certain endpoints are called (and how many times), but also allows you to fake responses through the flush method.
Here's a small snipet where I return a fake response for the localhost/data endpoint, where httpMock is an instance of HttpClientController, defined in beforeEach.
We can then use someCall to also test what data was send to the backend like this if you would like to do that.