How do I test a directive that requires a service provided by the host? #3753
-
I have a directive that needs a service that is provided by the host component. To ensure that it is provided by the host component, Iuse the @Directive({
selector: "[myDirective]",
standalone: true
})
export class MyDirective {
constructor(@Host() public readonly service: MyService) {}
} I am trying to test it like this: describe("my sandbox", () => {
beforeEach(async () => MockBuilder(MyDirective).mock(MyService));
it("should create", () =>
expect(MockRender(MyDirective).point.componentInstance).toBeTruthy());
}); but I get an error telling me that there is no provider for I have a minimal reproduction of the problem here. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
you can provide import {Directive, Host, Injectable,} from '@angular/core';
import {MockBuilder, MockProvider, MockRender} from 'ng-mocks';
@Injectable()
class MyService {}
@Directive({
selector: "[myDirective]",
standalone: true
})
export class MyDirective {
constructor(@Host() public readonly service: MyService) {}
}
describe('my sandbox', () => {
beforeEach(() => MockBuilder(MyDirective));
it("should create", () => {
const fixture = MockRender(MyDirective, null, {
providers: [
MockProvider(MyService),
],
});
expect(fixture.point.componentInstance.service).toBeDefined();
});
}); |
Beta Was this translation helpful? Give feedback.
Hi @Simon-TheHelpfulCat,
you can provide
MyService
inMockRender
, in this case it will be considered asHost
injection: https://codesandbox.io/s/upbeat-ioana-fzqdkj?file=/src/test.spec.ts:474-534