【问题标题】:TypeError: Cannot read property 'markForCheck' of undefined Angular6 Impure Pipe TestingTypeError:无法读取未定义的 Angular6 不纯管道测试的属性“markForCheck”
【发布时间】: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


    【解决方案1】:

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

    pipe = new NaturalType(changeDetector, ngZone);  
    

    在 beforeEach 块中创建了一个新的 NaturalType 和一个未定义的 changeDetector

    【讨论】:

    • 我试图研究如何初始化它,但没有成功。你能提供任何例子吗?我试图查看页面angular.io/guide/testing 并尝试了其他一些事情。如果您可以重写我的管道测试用例文件并作为答案发布,那就太好了。提前谢谢!!!
    猜你喜欢
    • 2020-01-17
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    相关资源
    最近更新 更多