Reputation: 45
Suppose i want to write a unit test for a service which depends on services of another module.
Now here is my question. Is there any way to write my test so that i mock the module that MyService
depends on such that i can use it in my unit test like this:
const moduleRef = await Test.createTestingModule({
imports: [
MockedModule,
],
providers: [
MyService,
],
});
Or i have to write a mock for each dependency service and use them like this:
const moduleRef = await Test.createTestingModule({
providers: [
MyService,
{
provider: DependencyService,
useClass: DependencyServiceMock,
}
],
});
Upvotes: 0
Views: 819
Reputation: 70570
I suppose it would be possible to use a MockModule
that provides and exports the same dependencies that the service would normally depend on. I haven't heard of someone trying that yet, but I don't see why it wouldn't work. So if you have
@Injectable()
export class MyService {
constructor(private readonly depService: DependencyService) {}
...
}
Then in your mock module you would need
@Module({
providers: [{
provide: DependencyService,
useClas: DependencyServiceMock,
}],
exports: [DependencyService],
})
export class MockedModule {}
And in your test you would need to do
beforeEach(async () => {
const app = await Test.createTestModule({
imports: [MockedModule],
providers: [MySerivce],
}).compile();
});
...
Upvotes: 1