Currently, I am attempting to replicate a well-known process in Java development using TypeScript and JEST for practice. In this scenario, there is a Controller
class that relies on a Service
class. The connection between the two is established through the constructor of the Controller
, making the presence of the Service
mandatory.
To manage dependencies at runtime, I utilize a Dependency Injection (DI) library called tsyringe
. This ensures that the DI container handles the instantiation of the Service
and its injection into the Controller
when required.
Here is the source code for the Controller
:
import { scoped, Lifecycle } from "tsyringe";
import { RouteService } from "./RouteService";
import { RouteDTO } from "./view/RouteDTO";
@scoped(Lifecycle.ContainerScoped)
export class RouteController {
constructor(private routeService: RouteService) {}
public createRoute(route: RouteDTO): RouteDTO {
// business logic - meant for testing
if (isBusinessLogicValid) {
return this.routeService.saveRoute(route);
} else {
throw Error("Invalid business logic");
}
}
}
And here is the source code for the Service
:
import { scoped, Lifecycle } from "tsyringe";
import { UserSession } from "../user/UserSession";
import { RouteDTO } from "./view/RouteDTO";
@scoped(Lifecycle.ContainerScoped)
export class RouteService {
constructor(
private userSession: UserSession
) {}
public saveRoute(route: RouteDTO): RouteDTO {
// contains business logic and handling persistence
return route;
}
}
I am striving to mock the RouteService
class in a manner that eliminates the need for manual creation of an instance for unit testing purposes with the RouteController
. If done manually, it would involve resolving all underlying dependencies (i.e., RouteController
depends on RouteService
, RouteService
depends on UserSession
, and so forth).
In Java, utilizing Mockito allows me to achieve something similar as shown below:
RouteService routeServiceMock = mock(RouteService.class);
// defining mock behavior on routeServiceMock
RouteController controller = new RouteController(routeServiceMock);
RouteDTO newDTO = createRouteDTO();
RouteDTO savedDTO = controller.save(newDTO);
assertThat(savedDTO).isEqualTo(newDTO);
//... other assertions
Upon reviewing Jest documentation, I have not found an equivalent approach. Is there a way to accomplish this? If yes, could someone provide guidance on how to proceed?