TypeError:无法读取未定义的Angular6不纯管道测试的属性'markForCheck'

时间:2018-08-25 03:53:17

标签: javascript angular unit-testing jasmine angular6

我正在尝试使用茉莉花测试不纯净的烟斗。该管道可在ng服务上正常工作,并可以完成其为文本设置动画的预期工作。

在测试用例中创建它的实例并尝试运行tranform方法时,会出现错误。

  

NaturalTypePipe>将“ abc”转换为“ abc”   TypeError:

     

无法读取未定义的属性“ markForCheck”       在       NaturalType ../ src / app / shared / pipes / natural-type.pipe.ts.NaturalType.typeNextCharacter

我的测试用例文件如下:-

import { ChangeDetectorRef, NgZone } from '@angular/core';
import { NaturalType } from './natural-type.pipe';

describe('NaturalTypePipe', () => {
    let changeDetector: ChangeDetectorRef;
    let ngZone: NgZone;
    let pipe: NaturalType;

    beforeEach(() => {
        pipe = new NaturalType(changeDetector, ngZone);  
    });

    it('should create an instance of natural pipe', () => {
        expect(pipe).toBeTruthy();
    });

    it('transforms "abc" to "abc"', () => {
        expect(pipe.transform('abc')).toBe('abc');
    });
});

我的管道代码如下:-

import { Pipe, PipeTransform, ChangeDetectorRef, NgZone } from '@angular/core';

/*
 * Animating text as if it was being typed by a user
*/

@Pipe({name: 'naturalType', pure: false})
export class NaturalType implements PipeTransform {
   private typed: string = '';
   private target: string = '';
   private currentIndex: number = -1;
   private timeoutHandle: number = -1;

   constructor( private changeDetector: ChangeDetectorRef, private ngZone: NgZone ) { }

   transform(value: string, mintypingSpeed: number = 30): any {
      if (this.target !== value) {
       clearTimeout(this.timeoutHandle);
       this.typed = '';
       this.currentIndex = -1;
       this.target = value;
       this.typeNextCharacter(mintypingSpeed);
      }
      return this.typed;
   }
   
   private typeNextCharacter(mintypingSpeed: number) {
    this.currentIndex++;
    this.typed = this.target.substr(0, this.currentIndex);
    this.changeDetector.markForCheck();
    if (this.typed !== this.target) {
      const time = Math.round(Math.random() * 70) + mintypingSpeed;
      this.ngZone.runOutsideAngular(() => {
        this.timeoutHandle = <any> setTimeout(()=> {
          this.ngZone.run(() => this.typeNextCharacter(mintypingSpeed));
        },time);
      });  
    }
   }
}

我最初的想法是这可能是由于管道文件中的私有构造函数变量和私有typeNextCharacter方法所致,我尝试了一些尝试但未成功。

任何帮助将不胜感激。预先感谢。

1 个答案:

答案 0 :(得分:0)

changeDetector变量从未初始化。所以,这行:

pipe = new NaturalType(changeDetector, ngZone);  

beforeEach块中的新NaturalType和一个未定义的changeDetector