【发布时间】:2018-08-25 03:53:17
【问题描述】:
我正在尝试使用茉莉花测试不纯的管道。管道在 ng serve 上运行良好,并完成了动画文本的预期工作。
当我在测试用例中创建它的实例并尝试运行 tranform 方法时出现错误。
NaturalTypePipe > 将“abc”转换为“abc” 类型错误:
无法读取未定义的属性“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 方法,我尝试了一些但没有成功。
任何帮助将不胜感激。提前致谢。
【问题讨论】:
标签: javascript angular unit-testing jasmine angular6