1

My Angular 5 component uses typeahead directive of ngx-bootstrap, like this:

<input [(ngModel)]="inputted"
   [typeahead]="days"
   (typeaheadOnSelect)="select($event)"
   class="form-control">

Now I want to test that my component does what is expected when the user selects an item in the typeahead. I need to simulate the typeahead directive's typeaheadOnSelect output. How can I access the directive in my unit test, to manually emit a typeaheadOnSelect event? This far I have come to this point:

const elem: DebugElement = fixture.debugElement.query(By.css('input'));

which gives me the input element. How do I find the underlying typeahead directive from there?

1 Answer 1

3

As explained in this answer, directive instances can be retrieved from injector:

import { TypeaheadDirective } from 'ngx-bootstrap';

...
const elem: DebugElement = fixture.debugElement.query(By.css('input'));
const dir = elem.injector.get(TypeaheadDirective);

A proper way is to isolate unit tests from third-party units and provide stubs for ngx-bootstrap directives instead of importing its module. A stub can optionally expose its externals as local variables instead of using injector to get class instances:

let typeaheadOutput;

...
@Directive({ selector: '[typeahead]' }
class TypeaheadDirectiveMock {
  @Input() typeahead;
  @Output() typeaheadOnSelect = typeaheadOutput = new EventEmitter();
}

TestBed.configureTestingModule({ declarations: [TypeaheadDirectiveMock], ...})
.compileComponents();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.