【问题标题】:Unit Tests with Angularfire2 on angular-cli在 angular-cli 上使用 Angularfire2 进行单元测试
【发布时间】:2017-08-07 07:40:55
【问题描述】:

使用 angular-cli 创建了一个新的 angular 2 项目

下面是默认组件app.component.ts,它有app.component.spec.ts

import { Component } from '@angular/core';
import { AngularFire } from 'angularfire2'; // import angularfire2

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  af: AngularFire;
  constructor(af: AngularFire){
    this.af=af;
    this.firebaseCall();
  }
  //push data to firebase collection
  firebaseCall(){
    let post=this.af.database.list('/post');
    post.push({a:'test'});
  }

}

在 app.component.spec.ts 中为上述 firebaseCall() 实施单元测试

我在 app.component.spec.ts 的下面几行添加/更新了

import { AngularFire } from 'angularfire2';
beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,AngularFire // extra added
      ],

    });
    TestBed.compileComponents();

  });

在 ng 测试时出现以下错误

模块“DynamicTestModule”声明的意外值“AngularFire”

【问题讨论】:

  • 查看 AngularFire2 源代码,了解如何配置 TestBedgithub.com/angular/angularfire2/blob/2.0.0-beta.8/src/…
  • 添加此行导入:[AngularFireModule.initializeApp(COMMON_CONFIG)] 收到此错误异步回调未在 jasmine.DEFAULT_TIMEOUT_INTERVAL 指定的超时内调用。

标签: unit-testing angular angular-cli angularfire2


【解决方案1】:

您需要在测试中模拟服务。 在这里你正在注入AngularFire。所以你的测试设置应该是这样的。

    import { AngularFire } from 'angularfire2';
...
   const mockFirebase = jasmine.createSpyObj('af',['database']);
   af.database.and.returnValue({list: Rx.Observable.of([])});   
    beforeEach(() => {
        TestBed.configureTestingModule({
          declarations: [
            AppComponent
          ],
          providers:[
          {provide:AngularFire, useValue:}]
        });
        TestBed.compileComponents();

      });

希望这对您有所帮助。始终在单元测试中模拟您的提供程序,并且不要进行 http 调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 2016-08-14
    • 2017-03-07
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多