angular - 如何在 Angular 组件内提供/模拟 Angularfirestore 模块以通过默认测试?

标签 angular testing angularfire2

如何在我的 app.component 中提供 AngularFirestore 模块,以便我的默认 toBeTruthy() 测试能够通过?

Error: StaticInjectorError(DynamicTestModule)[AppComponent -> AngularFirestore]: 
      StaticInjectorError(Platform: core)[AppComponent -> AngularFirestore]: 
        NullInjectorError: No provider for AngularFirestore!

app.component

export class AppComponent implements OnInit {
  private notesCollection: AngularFirestoreCollection<any>;
  public notes: Observable<any[]>;

  constructor(private afs: AngularFirestore) {}

  ngOnInit() {
    this.notesCollection = this.afs.collection('notes');
    this.notes = this.notesCollection.valueChanges();
  }
}

这只是默认测试:

class FirebaseMock implements AngularFirestore {
  app: FirebaseApp;
  firestore: FirebaseFirestore;
  persistenceEnabled$: Observable<boolean>;

  collection<T>(path: string, queryFn?: QueryFn): AngularFirestoreCollection<T> {
    return undefined;
  }

  doc<T>(path: string): AngularFirestoreDocument<T> {
    return undefined;
  }

  createId(): string {
    return undefined;
  }
}

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(
    async(() => {
      TestBed.configureTestingModule({
        imports: [
          RouterTestingModule,

        ],
        declarations: [ AppComponent ],
        providers: [
          {
            provide: AngularFirestoreModule,
            useClass: FirebaseMock
          },
        ],
      }).compileComponents();
    }),
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

最佳答案

您必须要么模拟“AngularFirestore”,要么按原样注入(inject)它并监视它的方法,这样它就不会被调用。我不会推荐第二个选项,因为它需要注入(inject)真正的服务,而这可能也依赖于其他服务。因此,您还必须注入(inject)它们,这可能最终需要数百万个服务来测试一个组件。因此,让我们选择第一个选项。

如果它在您的组件中经常使用,我建议您为这些类型的服务创建一个“ stub ”模块,并将该模块导入到您要测试的组件测试模块中。如果只是为了这个组件,你可以像这样创建一些简单的东西:(让我们先从简单的开始,然后再创建模块)

app.component.spec.ts

describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;

    const AngularFirestoreStub = {
        // I just mocked the function you need, if there are more, you can add them here.
        collection: (someString) => {
            // return mocked collection here
        }
    };

    beforeEach(
        async(() => {
           TestBed.configureTestingModule({
               imports: [ RouterTestingModule],
               // I used 'useValue' because it is just a json. If it was class, I'd use 'useClass'
               providers: [{provide: AngularFirestore, useValue: AngularFirestoreStub}]
               declarations: [ AppComponent ]
           }).compileComponents();
        })
    );

    beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent); // Should be fine
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy(); // Should pass
    });
});

正如我之前所说,如果 AngularFirestore 是您的许多组件使用的服务,那么请在您的项目中的某处创建一个 stub 模块(在我的项目中,我创建了一个 testing 文件夹并将其放在 src 旁边)

CommonServiceModuleStub

@NgModule({
    providers: [{provide: AngularFirestore, useClass: AngularFirestoreStub}]
})
export class CommonServiceModuleStub {}

// I'd recommend you put this service in a subfolder.
// This time, I created a class instead of a json. 
// It is because, your other components may require more 'mocked' functions.
// It may be harder to maintain them within a json.
@Injectable()
export class AngularFirestoreStub {
    collection(someString) {
        // return mock collection;
    }
}

现在,不用自己提供,只需导入我们刚刚创建的模块

app.component.spec.ts

 ...
 TestBed.configureTestingModule({
     imports: [ RouterTestingModule, CommonServiceModuleStub],
     declarations: [ AppComponent ]
 }).compileComponents();

选项 2

有时,您的服务很简单,您不想费心去“ mock ”它们。看看下面的例子

app.component.ts

@Component({ ... })
export class AppComponent {
    constructor(private myService: AwesomeService) {}

    doSomethingCool() {
        this.myService.getAwesomeStuff();
    }
}

让我们先配置TestBed

app.component.spec.ts

 ...
 TestBed.configureTestingModule({
     imports: [ RouterTestingModule],
     // since, 'AwesomeService' is a service on its own and 
     // doesn't require other services, we easily provide it here
     providers: [ AwesomeService ]
     declarations: [ AppComponent ]
 }).compileComponents();

在测试中

it('should do something cool without getting awesome stuff', () => {
    spyOn(component.myService, 'getAwesomeStuff');
    // Note: if you want to spy on it and you want it to get called for real
    // you should do following
    // spyOn(component.myService, 'getAwesomeStuff').and.callThrough();
    // or return fake output
    // spyOn(component.myService, 'getAwesomeStuff')
    //        .and.callFake((arguments, can, be, received) =>  {
    //                          return fake;
    //                      });

    component.doSomethingCool();
    expect(component.myService.getAwesomeStuff).toHaveBeenCalled();
});

更多信息,你可以看看jasmine docs

关于angular - 如何在 Angular 组件内提供/模拟 Angularfirestore 模块以通过默认测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48760093/

相关文章:

angular - 尽管在现有模块中导入了 CommonModule,ngFor 仍无法工作

Angular 4 : Calling Regex patterns from an Object

angularjs - Protractor 找不到之前已找到 2 个测试的元素

AngularFireStorage 为每次上传返回未定义的 URL

angular - 检查用户是否仍在 angularfire2 中通过身份验证

firebase - angularfire2会将时间戳值转换为js Date吗?

angular - 在 Angular 2 中提交后如何清除表单?

css - Ng-Bootstrap active 药丸添加下拉不显示

debugging - 有没有办法在不同平台上测试 phonegap 构建应用程序

ruby-on-rails - rails 2.3.8 : How to functionally test the root route by requesting '/' ?