简体   繁体   中英

Angular 4 Jasmine Unit Test Directive Export Function

I have a created custom directive in angular 4 the directive is below.

import { Directive } from '@angular/core';
import { NG_VALIDATORS, FormControl } from '@angular/forms';
export function appValidator(control: FormControl) {
let tWordsLength = false;
if (control.value) {
let test = control.value.split(",");
var lengths = test.map(function (word) {
  if(word.length > 30){
    tWordsLength = true;
  }
  return word.length
})
if (test.length > 10 || tWordsLength) {
  return {
    tagsDomain: {
      parsedDomain: false
    }
  }
}
}
return null;
}
@Directive({
  selector: '[appGeneral][ngModel]',
   providers: [
   {
    provide: NG_VALIDATORS,
    useValue: appValidator,
    multi: true
   }
 ]
})
export class GeneralDirective {
};

And My spec is as below

import {TestBed} from '@angular/core/testing';
import { GeneralDirective } from './app-general.directive';
describe('GeneralDirective', () => {
beforeEach(() => {
 TestBed.configureTestingModule({
   declarations: [GeneralDirective]
  });
 });
 it('should create an instance', () => {
   const directive = new GeneralDirective();
   expect(directive).toBeTruthy();
  });
 });

I want to cover the unit testing for export function 'appValidator' in Directive. Can anyone suggest the way on how to achieve coverage on export function.

Coverage is easy

it('should cover the function', () => {
  appValidator(new FormControl(''));
});

If this is what you ask. But you should also test if your functions works as desired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM