...

/

Mocking Dependencies

Mocking Dependencies

Learn how to refactor code and mock dependencies.

When we write a unit test, we need to isolate our component that is being tested. We do this by faking or mocking parts of the system that it interacts with. There are several techniques we can use, including stubs, mocks, spies, and staging services. This lets us write focused unit tests that run fast and give us useful, targeted feedback in the event that they fail.

Single responsibility principle

Clean code is written in small classes, each with a single responsibility. Consider a large Angular component class with many functions that interact with a number of external services. This will be hard to test because when we write our unit tests, we need to mock all of these dependencies. A problem like this is called a code smell, a hint that something is wrong, and we should consider restructuring our code.

In this case, our solution could be to extract some related methods into a separate service. This lets us remove dependencies from our component class and ...