Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save belachkar/61dc0d8a8bcb0a88cdae6df7e50c47db to your computer and use it in GitHub Desktop.
Save belachkar/61dc0d8a8bcb0a88cdae6df7e50c47db to your computer and use it in GitHub Desktop.

Angular Testing Directive - Injection Dependecy

Fixing error: "arguments not provided"

Files

  • highlight.directive.ts
  • highlight.directive.spec.ts
  • menu.component.html

Code example

highlight.directive.ts

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  constructor(
    private el: ElementRef,
    private renderer: Renderer2
  ) { }

  @HostListener('mouseenter')
  onMouseEnter() {
    this.renderer.addClass(this.el.nativeElement, 'highlight');
  }

  @HostListener('mouseleave')
  onMouseLeave() {
    this.renderer.removeClass(this.el.nativeElement, 'highlight');
  }
}

highlight.directive.spec.ts

import { HighlightDirective } from './highlight.directive';
import { ElementRef, Renderer2 } from '@angular/core';
import { inject } from '@angular/core/testing';

describe('HighlightDirective', () => {
  it('should create an instance', () => {
  
    // Fixation of the error: "An argument for 'el' was not provided"
    inject([ElementRef, Renderer2], (elementRef: ElementRef, renderer: Renderer2) => {
      const directive = new HighlightDirective(elementRef, renderer);
      expect(directive).toBeTruthy();
    });
  });
});

menu.component.html

<div class="container" fxLayout="column" fxLayoutGap="10px">

  <div fxFlex>
    <div>
      <h3>Menu</h3>
      <hr>
    </div>
  </div>

  <div fxFlex *ngIf="dishes" [@expand]>
    <mat-grid-list cols="2" rowHeight="200px">
      
      <!-- The "appHighlight" directive -->
      <mat-grid-tile appHighlight
        *ngFor="let dish of dishes"
        [routerLink]="['/dishdetail', dish.id] ">
        <img matListAvatar height="200px" src="{{BaseURL + dish.image}}" alt="{{dish.name}}">
        <mat-grid-tile-footer>
          <h1 matLine>{{dish.name | uppercase}}</h1>
        </mat-grid-tile-footer>
      </mat-grid-tile>
    </mat-grid-list>
  </div>

  <!-- Spinner -->
  <div fxFlex [hidden]="dishes || errMsg">
    <mat-spinner></mat-spinner>
    <h4>Loading... Please wait!</h4>
  </div>

  <!-- Display error messages -->
  <div fxFlex *ngIf="errMsg">
    <h2>Errors</h2>
    <h4>{{errMsg}}</h4>
  </div>

</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment