小编Vo *_*oan的帖子

如何在单元测试中模拟 ApplicationRef

我试图通过 Jasmine 和 Angular 4 测试这两种方法,但this.applicationRef总是返回一个空对象。这个怎么解决?

这是我的代码:

@Injectable()
class Dialog {
  ....
  getRootViewContainerRef(): ViewContainerRef {
    const appInstance = this.applicationRef.components[0].instance;

    if (!appInstance.viewContainerRef) {
      const appName = this.applicationRef.componentTypes[0].name;
      throw new Error(`Missing 'viewContainerRef' declaration in ${appName} constructor`);
    }

    return appInstance.viewContainerRef;
  }
}

createOverlay(parentContainerRef: ViewContainerRef): ComponentRef<DialogContainerComponent> {
  const rootContainerRef = parentContainerRef;
  const rootInjector = rootContainerRef.injector;

  const bindings = ReflectiveInjector.resolve([]);
  const injector = ReflectiveInjector.fromResolvedProviders(bindings, rootInjector);

  const overlayFactory = this.cfr.resolveComponentFactory(DialogContainerComponent);
  return rootContainerRef.createComponent(overlayFactory, rootContainerRef.length, injector);
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试脚本:

describe('Dialog service', () => {
  //let fixture: ComponentFixture<DialogInformationComponent>; …
Run Code Online (Sandbox Code Playgroud)

angular angular-test

4
推荐指数
1
解决办法
3098
查看次数

标签 统计

angular ×1

angular-test ×1