I am looking at this example for displaying components based on the role of a user: https://blog.strongbrew.io/display-a-component-based-on-role/
My code won't compile because of missing arguments in my constructor inside has-role.directive.spec.ts
. From has-role.directive.ts
it takes 3 arguments: ViewContainerRef and TemplateRef from angular core, and a service for getting user roles.
has-role.directive.ts
constructor(
private viewContainerRef: ViewContainerRef,
private templateRef: TemplateRef<any>,
private authenticationService: AuthenticationService)
But inside the example tutorial its used like this:
has-role.directive.spec.ts
describe('HasRoleDirective', () => {
it('should create an instance', () => {
const directive = new HasRoleDirective();
expect(directive).toBeTruthy();
});
});
How can this in the example work, but for me it complains about missing arguments?
As Michał suggested i created classes to add to the constructor:
class TestViewContainerRef extends ViewContainerRef {
element: ElementRef<any>;
injector: Injector;
parentInjector: Injector;
clear(): void {
throw new Error('Method not implemented.');
}
get(index: number): ViewRef {
throw new Error('Method not implemented.');
}
length: number;
createEmbeddedView<C>(templateRef: TemplateRef<C>, context?: C, index?: number): EmbeddedViewRef<C> {
throw new Error('Method not implemented.');
}
createComponent<C>(componentFactory: ComponentFactory<C>, index?: number, injector?: Injector, projectableNodes?: any[][], ngModule?: NgModuleRef<any>): ComponentRef<C> {
throw new Error('Method not implemented.');
}
insert(viewRef: ViewRef, index?: number): ViewRef {
throw new Error('Method not implemented.');
}
move(viewRef: ViewRef, currentIndex: number): ViewRef {
throw new Error('Method not implemented.');
}
indexOf(viewRef: ViewRef): number {
throw new Error('Method not implemented.');
}
remove(index?: number): void {
throw new Error('Method not implemented.');
}
detach(index?: number): ViewRef {
throw new Error('Method not implemented.');
}
}
let viewContainerRefMock = {
viewContainerRef: TestViewContainerRef
};
describe('HasRoleDirective', () => {
it('should create an instance', () => {
const directive = new HasRoleDirective(viewContainerRefMock, templateRefMock, authenticationServiceMock);
expect(directive).toBeTruthy();
});
});
Well, obviously you are missing some arguments as the error message describes. When using the directive in your application, angular creates those 3 dependencies and injects them into your directive.
In your example, you are creating an instance of your directive inside a test. Angular can't inject those dependencies because there is no Angular, it is a test. Since Angular is not providing them, you should provide them manually. This is explained here.
The reason the blog you are referring to does not need them is that that blog does not unit test it.