Angular 6管道不支持构造函数

时间:2018-06-09 05:53:50

标签: angular angular-pipe

这是我的date-formatter-by-timezone.pipe.ts管道

import { Pipe, PipeTransform } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';

@Pipe({
  name: 'dateFormatterSecByTimezone'
})
export class DateFormatterSecByTimezonePipe implements PipeTransform {

  constructor(private cookieService: CookieService) {}

  timezone:any = parseInt(this.cookieService.get('TM_Z')) * 1000;

  caculateTime(date , timezone){
    //some code here ...
  }

  transform(date: any){
     return this.caculateTime(date , this.timezone)
  }
}

这是spec文件date-formatter-sec.pipe.spec.ts

import { DateFormatterSecByTimezonePipe } from './date-formatter-sec-by- 
timezone.pipe';

describe('DateFormatterSecByTimezonePipe', () => {
  it('create an instance', () => {
    const pipe = new DateFormatterSecByTimezonePipe();
    expect(pipe).toBeTruthy();
  });
});

在spec文件中我收到此错误:

Expected 1 argument, but got 0.
(alias) new DateFormatterSecByTimezonePipe(cookieService: CookieService): 
DateFormatterSecByTimezonePipe
import DateFormatterSecByTimezonePipe

但是当我使用上面那个编辑器建议的代码时,它仍然无效! 我在管道中导入了构造函数,因为我需要在此管道中使用cookie数据。我该如何解决这个错误?

2 个答案:

答案 0 :(得分:1)

错误不是来自Angular,这是一个简单的Typescript问题:你有一个带有参数的构造函数,但在你的测试中你没有传递参数。这个论点通常由Angular中的DI提供。从测试文档(参见下面的链接):

  

作为服务消费者,您不必担心任何此类问题。您不必担心构造函数参数的顺序或它们是如何创建的。   作为服务测试人员,您必须至少考虑第一级服务依赖关系,但是当您使用TestBed测试实用程序提供和创建服务时,您可以让Angular DI执行服务创建并处理构造函数参数顺序。

因此,您可以使用

修复此特定测试
const pipe = new DateFormatterSecByTimezonePipe(null);

但是一旦你想编写实际断言管道行为的测试,这将不会非常有用。管道本质上就像一个服务。如果服务不需要依赖项,您可以在测试中自己实例化服务,也可以在测试中构建依赖项。如果您希望Angular使用DI来实例化服务,则需要使用其工具:

https://angular.io/guide/testing

本文还介绍了使用间谍等方法。

答案 1 :(得分:0)

您可能希望看到此similiar question on SO

摘要是您应该执行以下操作:

import {SafeHtmlPipe} from './safe-html.pipe';
import {inject} from '@angular/core/testing';
import {DomSanitizer} from '@angular/platform-browser';


describe('SafeHtmlPipe', () => {
  it('create an instance', inject([DomSanitizer], (sanitize: DomSanitizer) => {

    const pipe = new SafeHtmlPipe(sanitize);
    expect(pipe).toBeTruthy();
  }));
});
相关问题