Directive unit testing fails

936 views Asked by At

I am using jest.js for testing with my angular app. here is the directive I use in html:

<textarea errorHighlighter formControlName="Url" name="Url" cols="50" rows="5"
                                placeholder="Enter Page URL" (ngModelChange)="pageUrlChanges($event)"></textarea>

here is my directive.ts file:

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

@Directive({
  selector: '[errorHighlighter]'
})
export class ErrorHighlighterDirective {

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

  @HostListener('input') oninput() {
    if (this.el.nativeElement && this.control) {
      if (this.control.control.status === 'INVALID') {
        this.renderer.addClass(this.el.nativeElement, 'has-err');
      } else {
        this.renderer.removeClass(this.el.nativeElement, 'has-err');
      }
    }
  }

}

this is written to show the error border around the input field. I am trying to test the same like this:

import { ErrorHighlighterDirective } from './error-highlighter.directive';
import { Directive, ElementRef, SimpleChanges, HostListener, Renderer2, Component, DebugElement } from '@angular/core';
import { NgControl, FormGroup, FormsModule, FormControl, ReactiveFormsModule } from '@angular/forms';
import { TestBed, ComponentFixture } from '@angular/core/testing';

@Component({
    template: `<input errorHighlighter formControlName="Url" type="text">`
})
class TestHighlighterComponent { }



describe('ErrorHighlighterDirective', () => {

    let component: TestHighlighterComponent;
    let fixture: ComponentFixture<TestHighlighterComponent>;
    let inputEl: DebugElement;

    const fg: FormGroup = new FormGroup({
        'Url': new FormControl('')
    });

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [TestHighlighterComponent, ErrorHighlighterDirective],
            imports: [FormsModule, ReactiveFormsModule],
            providers: [
                { provide: NgControl, useValue: fg }
            ]
        });
        fixture = TestBed.createComponent(TestHighlighterComponent);
        component = fixture.componentInstance;
        inputEl = fixture.debugElement.query(By.css('input'));
    });


    it('should create an instance', () => {
        const directive = new ErrorHighlighterDirective(inputEl, fg, Renderer2);
        expect(directive).toBeTruthy();
    });

});

But the test not succeeds. getting error like below:

● Test suite failed to run

    TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    src/app/directives/error-highlighter.directive.spec.ts:33:46 - error TS2304: Cannot find name 'By'.

    33         inputEl = fixture.debugElement.query(By.css('input'));
                                                    ~~
    src/app/directives/error-highlighter.directive.spec.ts:38:66 - error TS2345: Argument of type 'FormGroup' is not assignable to parameter of type 'NgControl'.
      Type 'FormGroup' is missing the following properties from type 'NgControl': name, valueAccessor, viewToModelUpdate, control, path

    38         const directive = new ErrorHighlighterDirective(inputEl, fg, Renderer2);

Any one help me to understand and fix these issue? I am not much familiar with angular test either jest.js.

1

There are 1 answers

2
Narendra On BEST ANSWER
  1. You can use By.directive e.g.
const directiveEl = fixture.debugElement.query(By.directive(MyDirective));
expect(directiveEl).not.toBeNull();
  1. You need to import By from angular.platform-browser

    import { By } from '@angular/platform-browser

You can further read here.

You can use any selector By.css that you can use with css. And a selector for a class is simply .classname. e.g.

By.css(.classname)

or

By.css('input[type=radio]')

or

By.css('textarea')