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



我正在尝试使用茉莉花测试不纯的管道。管道在 ng serve 上工作正常,并完成其预期的动画文本工作。

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

NaturalTypePipe>将"abc">

转换为"abc" 类型错误:

无法读取未定义的属性"标记检查" 在 自然型../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);
});  
}
}
}

我最初的想法是这可能是由于管道文件中的私有构造函数变量和私有类型NextCharacter 方法,我尝试了一些事情但没有成功。

任何帮助将不胜感激。提前谢谢。

changeDetector变量永远不会被初始化。所以,这行:

pipe = new NaturalType(changeDetector, ngZone);  

在之前每个块都在创建一个具有未定义changeDetector的新NaturalType

最新更新