Automock is a standalone library for unit testing. Using TypeScript Reflection
API (reflect-metadata) internally to produce mock objects, Automock streamlines
test development by automatically mocking class external dependencies.
infoAutomock is a third party package and is not managed by the NestJS core team.
Please, report any issues found with the library in the appropriate repository
The dependency injection (DI) container is an essential component of the Nest module system.
This container is utilized both during testing, and the application execution.
Unit tests vary from other types of tests, such as integration tests, in that they must
fully override providers/services within the DI container. External class dependencies
(providers) of the so-called "unit", have to be totally isolated. That is, all dependencies
within the DI container should be replaced by mock objects.
As a result, loading the target module and replacing the providers inside it is a process
that loops back on itself. Automock tackles this issue by automatically mocking all the
class external providers, resulting in total isolation of the unit under test.
const{ unit, unitRef }= TestBed.create(CatsService).compile();
Calling .compile() returns an object with two properties, unit, and unitRef.
unit is the unit under test, it is an actual instance of class being tested.
unitRef is the "unit reference", where the mocked dependencies of the tested class
are stored, in a small container. The container's .get() method returns the mocked
dependency with all of its methods automatically stubbed (using jest.fn()):
const{ unit, unitRef }= TestBed.create(CatsService).compile();let httpServiceMock: jest.Mocked<HttpService>= unitRef.get(HttpService);
info The .get() method can accept either a string or an actual class (Type) as its argument.
This essentially depends on how the provider is being injected to the class under test.
Providers are one of the most important elements in Nest. You can think of many of
the default Nest classes as providers, including services, repositories, factories,
helpers, and so on. A provider's primary function is to take the form of an
Injectable dependency.
Consider the following CatsService, it takes one parameter, which is an instance
of the following Logger interface:
TypeScript's Reflection API does not support interface reflection yet.
Nest solves this issue with string-based injection tokens (see Custom Providers):
Nest is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd like to join them, please read more here.