对依赖于服务的管道进行角度单元测试

时间:2018-10-24 13:55:54

标签: angular angular-unit-test

我正在尝试对具有服务依赖性的管道进行单元测试。

.spec.ts文件中,问题是此行:

pipe = new BoolStringPipe()

错误是:

  

预期有1个参数,但有0个

此错误是因为管道具有注入服务的构造函数。

如何在单元测试期间将服务注入管道?谢谢

我的全部相关代码如下。

管道代码:

import { Pipe, PipeTransform } from '@angular/core'
import { SfTranslate } from '@shared/sf-translate'

@Pipe({
  name: 'boolString'
})

export class BoolStringPipe implements PipeTransform {

  constructor(private translate: SfTranslate) {} // SERVICE INJECTED HERE

  transform(value: boolean, trueString: string = 'GUIBundle.generic.yes', falseString: string = 'GUIBundle.generic.no'): string {
    trueString = this.translate.transSafe(trueString)
    falseString = this.translate.transSafe(falseString)
    return value ? trueString : falseString
  }
}

规格文件:

import { BoolStringPipe } from './bool-string.pipe'

describe('BoolStringPipe', () => {
  let pipe: BoolStringPipe

  beforeEach(() => {
    pipe = new BoolStringPipe() // PROBLEM IS HERE BECAUSE THE CONSTRUCTOR NEEDS TO INJECT A SERVICE
  })

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

1 个答案:

答案 0 :(得分:0)

这有效:

import { inject, TestBed } from '@angular/core/testing'
import { SfTranslate } from '../../sf-translate'
import { BoolStringPipe } from './bool-string.pipe'

describe('BoolStringPipe', () => {
  let pipe: BoolStringPipe

  beforeEach(() => {
    // pipe = new BoolStringPipe()
    TestBed
      .configureTestingModule({
        providers: [SfTranslate]
      })
  })

  it('should create an instance', inject([SfTranslate], (translate: SfTranslate) => {
    pipe = new BoolStringPipe(translate)
    expect(pipe).toBeTruthy()
  }))
})