Creating a Mock Backend
Faking responses from a server to isolate unit tests
PROModule Outline
- Source Code & Resources PRO
- Lesson 1: Introduction PUBLIC
- Lesson 2: Introduction to Test Driven Development PUBLIC
- Lesson 3: Testing Concepts PUBLIC
- Lesson 4: Jest and Cypress PRO
- Lesson 5: A Simple Unit Test PRO
- Lesson 6: A Simple E2E Test PRO
- Lesson 7: Introduction to Angular's TestBed PRO
- Lesson 8: Setting up Tests with Jest and Cypress PUBLIC
- Lesson 9: Test Development Cycle PRO
- Lesson 10: Setting up Cypress & Jest in an Ionic/Angular Project PRO
- Lesson 11: The First Tests PRO
- Lesson 12: Injected Dependencies & Spying on Function Calls PRO
- Lesson 13: Building out Core Functionality PRO
- Lesson 14: Testing Asynchronous Code PRO
- Lesson 15: Creating a Mock Backend PRO
- Lesson 16: Setting up the Server PRO
- Lesson 17: Testing Integration with a Server PRO
- Lesson 18: Testing Storage and Reauthentication PRO
- Lesson 19: Refactoring with Confidence PRO
- Lesson 20: Conclusion PRO
Lesson Outline
Creating a Mock Backend
We keep hitting on the point that a unit test should be isolated - nothing comes in, and nothing goes out. If the unit test requires some input from an external dependency then we supply it with fake data.
In order to keep with this principle, we have been substituting our injected dependencies with mocked versions, like this:
providers: [
{ provide: ModulesService, useValue: {/* etc */} },
{ provide: NavController, useValue: {/* etc */} },
];
In tests that we are about to create, we will be dealing with code that makes an HTTP request to a server. We don't want the code in that test to actually send a request to our real server, we just want to check that the individual unit is doing its job - not that the entire system is working (again, that's not the role of a unit test).
When we want to make HTTP requests, we inject the HttpClient
service into our constructor. Given the approach we have been using for mocking services so far, you would be correct in assuming that you should do something like this:
providers: [
...
{ provide: HttpClient, useValue: {/* etc */} },
...
]
Thanks for checking out the preview of this lesson!
You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).