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

前端 未结 1 1429
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 21:17

I am using angular2 rc 5, I have written a custom pipe that fetches value from a json. The custom pipe : literal.pipe.ts looks like :

import {Pipe, PipeTrans         


        
相关标签:
1条回答
  • 2021-01-14 21:50

    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";
    
    
    0 讨论(0)
提交回复
热议问题