Angular 2 rc5 , unit testing issue with pipes that use injection

半世苍凉 提交于 2019-12-01 11:34:12

The problem here is that you are using TeseBed incorrectly. The example below is modified version of your literal.pipe.spec.ts file.

Main bit is that you have to reset test environment before initialising it.


    TestBed.resetTestEnvironment();

Once environment is reset the the configureTestingModule has to be configured:


    TestBed
    .initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting())
    .configureTestingModule({providers: [MessageService],imports: [HttpModule]});

import {By}             from '@angular/platform-browser';
import {provide}        from '@angular/core';
import {ViewMetadata}   from '@angular/core';
import {LiteralPipe} from './pipe/literal.pipe';
import {MessageService} from '../services/message.service';
import {Http} from '@angular/http';
import {inject, TestBed} from '@angular/core/testing';
import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from "@angular/platform-browser-dynamic/testing";
import {HttpModule} from '@angular/http';

let pipe: LiteralPipe;
let msgService: MessageService;
////////  SPECS  /////////////
describe('LiteralPipe', () => {
  beforeEach(() => {
    // Must reset the test environment before initializing it.
    TestBed.resetTestEnvironment();

    TestBed
      .initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting())
      .configureTestingModule({
        declarations: [],
        providers: [
          MessageService
        ],
        imports: [
          HttpModule
        ]
      });
  });
  
  it('transforms "Home.title" to "Login"', inject([MessageService], (msgService: MessageService) => {
    let pipe = new LiteralPipe(msgService);
    expect(pipe.transform('Home.title', null)).toEqual('Login');
  })
  );
});


Also there is a problem with your pipe implementation itself. You should check if args variable is not null before trying to get value from it.

literal.pipe.ts



    if(this.messageBundle[value])
          return this.messageBundle[value];
        else if(args != null && args[0])
          return args;
        else
          return "String not available. Pls include in bundle.json";

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!