unit-testing - Angular 2 rc5,使用注入(inject)的管道的单元测试问题

标签 unit-testing angular jasmine angular2-injection

我正在使用 angular2 rc 5,我编写了一个从 json 中获取值的自定义管道。自定义管道:literal.pipe.ts 看起来像:

import {Pipe, PipeTransform, Inject} from '@angular/core';
import {MessageService} from '../service/message.service';

@Pipe({
  name: 'literalString',
  pure: false
})
export class LiteralPipe  implements PipeTransform{

private messageBundle:any;
private request:any;

    constructor(private _messageService: MessageService){
        this._messageService = _messageService;
        this.messageBundle = {};
    }

    transform(value:string, args:string[]):any {
        if(!this.request){
            this.request = this._messageService.getBundle();
            this.request.subscribe(
                (data:any) => this.messageBundle = data
             );
        }

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

消息服务.ts:

import {Injectable} from "@angular/core"
import {Http} from '@angular/http';
import 'rxjs/Rx'

@Injectable()
export class MessageService{
    http:any;
    constructor(http: Http){
        this.http = http;
    }
    getBundle (){
        return this.http.get('../src/bundle.json').map((res:any) => res.json());
    }
}

Bundle.json 的键值对为

{
            "Home.title": "Login",
            "DashBoard.Title": "Dashboard",
            "CheckOutGiftCard.Title": "GIFT CARD CHECKOUT"
}

我正在使用 liteServer 运行我的单元测试。我的 unitTests.html:

<meta http-equiv="content-type" content="text/html;charset=utf-8">
  <title>Ng App Unit Tests</title>
  <link rel="stylesheet" href="../node_modules/jasmine-core/lib/jasmine-core/jasmine.css">
  <script src="../node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
  <script src="../node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
  <script src="../node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>
  <script src="node_modules/zone.js/dist/zone.js"></script>

  <script src="node_modules/reflect-metadata/Reflect.js"></script>

  <script src="node_modules/systemjs/dist/system.src.js"></script>

  <script src="systemjs.config.js"></script>
</head>
<body>
  <!-- Unit Testing Chapter #1: Proof of life.  -->
  <script>
    it('true is true', function(){ expect(true).toEqual(true); });
  </script>
  <script>
    // #2. Configure systemjs to use the .js extension
    //     for imports from the app folder
    System.config({defaultJSExtensions:true});
    // #3. Load and configure the TestComponentBuilder.
    // #2. Import the spec files explicitly
    Promise.all([
      System.import('app/literal.pipe.spec')
    ])
    // #3. wait for all imports to load ...
    //     then re-execute `window.onload` which
    //     triggers the Jasmine test-runner start
    //     or explain what went wrong.
    //System.import('app/literal.pipe.spec')
    .then(window.onload)
    .catch(console.error.bind(console));
  </script>
</body>
</html>

literal.pipe.spec.ts 如下:

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 '../service/message.service';
import {Http} from '@angular/http';
import { TestBed } from '@angular/core/testing';
//import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing';

// TestBed.initTestEnvironment(
//     BrowserDynamicTestingModule,
//     platformBrowserDynamicTesting()
//     );


  let pipe: LiteralPipe;
  let msgService: MessageService;
////////  SPECS  /////////////
describe('LiteralPipe', () => {
    beforeEach(()=>{
    [addProviders([MessageService]) ]
  });

 TestBed.configureTestingModule({
   declarations:[MessageService],
    providers: [{provide:MessageService, useClass:MessageService }  ],
    imports: [MessageService, Http]
  });
  it('can get an instance', inject([MessageService], (msgService: MessageService) => {
    //create instance of pipe using msgService as the instance of service. 
    pipe = new LiteralPipe(msgService);
  }));
  it('transforms "Home.title" to "Login"', () => {
    expect(pipe.transform('Home.title', null)).toEqual('Login');
  });
});

看起来我在规范文件的某个地方出错了,因为当我运行 npm test 并查看在浏览器中打开的单元测试时,我得到以下异常:

LiteralPipe can get an instance
TypeError: Cannot read property 'injector' of null
TypeError: Cannot read property 'injector' of null
    at TestBed._createCompilerAndModule (http://localhost:3000/node_modules/@angular/core/testing/test_bed.js:246:44)
    at TestBed._initIfNeeded (http://localhost:3000/node_modules/@angular/core/testing/test_bed.js:213:39)
    at TestBed.execute (http://localhost:3000/node_modules/@angular/core/testing/test_bed.js:274:14)
    at Object.eval (http://localhost:3000/node_modules/@angular/core/testing/test_bed.js:404:45)
    at attemptSync (http://localhost:3000/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1886:24)
    at QueueRunner.run (http://localhost:3000/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1874:9)
    at QueueRunner.execute (http://localhost:3000/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1859:10)
    at Spec.queueRunnerFactory (http://localhost:3000/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:697:35)
    at Spec.execute (http://localhost:3000/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:359:10)
    at Object.fn (http://localhost:3000/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:2479:37)
LiteralPipe transforms "Home.title" to "Login"
TypeError: Cannot read property 'transform' of undefined
TypeError: Cannot read property 'transform' of undefined
    at Object.eval (http://localhost:3000/app/literal.pipe.spec.js:30:20)
    at attemptSync (http://localhost:3000/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1886:24)

我应该更改什么才能使其正常工作。

最佳答案

这里的问题是您没有正确使用 TeseBed。下面的示例是 literal.pipe.spec.ts 文件的修改版本。

主要是你必须在初始化之前重置测试环境。


    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');
  })
  );
});


您的管道实现本身也存在问题。在尝试从中获取值之前,您应该检查 args 变量是否不为空。

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";

关于unit-testing - Angular 2 rc5,使用注入(inject)的管道的单元测试问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39018997/

相关文章:

ios - 如何在多个 OCUnit 测试用例之间共享代码?

javascript - 无法从 Angular 8 服务获取数据

javascript - Angular 5 Jasmine 测试,组件未编译

Backbone.js 和 Jasmine Spys 没有被调用

java - 如何让 Spark Streaming 在单元测试中计算文件中的单词数?

unit-testing - Xcode 4 : Application Tests in iOS Simulator

javascript - 一个函数即可订阅并返回值 - 提高函数纯度?

angular - 具有自定义全宽表单控件的 ionic 标签

javascript - 返回表达式类型 Promise<T> 不能分配给类型 Promise<T>?

python - 如何在 "Check iO"游戏中使用 tests.py 文件在本地测试代码