模拟子组件 - 多个组件将节点与标记名错误匹配

Mocking child components - multiple components match node with tagname error

我目前正在测试带有子组件 (BuilderNavbarComponent) 的组件 (BuilderComponent)。我想在我的测试中模拟子组件,但不断收到以下错误消息:多个组件匹配带有标签名 app-builder-navbar 的节点。解决此问题的最佳方法是什么?

describe('BuilderComponent', () => {
  let component: BuilderComponent;
  let store: MockStore;
  let initialState: IBuilder;
  let fixture: ComponentFixture<BuilderComponent>;
  const state = TEST_BUILDER_INITIAL_STATE;
  const reducers: ActionReducerMap<State> = { router: routerReducer };
  const metaReducers: MetaReducer<State>[] = !environment.production ? [logger] : [];

  interface State {
    router: fromRouter.RouterReducerState<BaseRouterStoreState>;
  }

  function logger(reducer: ActionReducer<State>): ActionReducer<State> {
    return (state, action) => {
      const result = reducer(state, action);
      console.groupCollapsed(action.type);
      console.log('prev state', state);
      console.log('action', action);
      console.log('next state', result);
      console.groupEnd();
      return result;
    };
  }

  beforeEach(() => {
    initialState = state;
  });

  @Component({
    selector: 'app-builder-navbar',
    template: '<div></div>',
  })
  class MockBuilderNavbarComponent {}

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [BuilderComponent, MockBuilderNavbarComponent],
      imports: [
        CommonModule,
        ToastrModule.forRoot(),
        ModalModule.forRoot(),
        QuillModule.forRoot(),
        EffectsModule.forRoot(),
        StoreModule.forRoot(reducers, {
          metaReducers,
          runtimeChecks: {
            strictActionImmutability: true,
            strictStateImmutability: true,
          },
        }),
        StoreModule.forFeature('builder', fromBuilder.reducer),
        AngularFirestoreModule,
        AngularFireModule.initializeApp(environment.firebaseConfig),
        ReactiveFormsModule,
        DirectivesModule,
        TooltipModule,
        ModalsModule,
        ShellModule,
        SharedModule,
        BuilderNavbarModule,
        BuilderBodyModule,
        HttpClientModule,
        RouterTestingModule.withRoutes([
          { path: 'preview', component: PreviewComponent },
          { path: 'builder', component: BuilderComponent },
        ]),
      ],
      providers: [
        provideMockStore({ initialState }),
        BuilderService,
        ToastrService,
        BsModalRef,
        UserService,
        QuillService,
      ],
    }).compileComponents();
  });

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

  describe('onResize()', () => {
    it('should trigger event when window is resized', () => {
      spyOn(component, 'onResize');
      spyOn(component, 'getViewportSize');
      window.dispatchEvent(new Event('resize'));
      expect(component.onResize).toHaveBeenCalled();
      component.onResize();
      expect(component.getViewportSize).toHaveBeenCalled();
    });
  });

  describe('ngOnInit()', () => {
    it('should retrieve values from store', () => {
      fakeAsync(() => {
        const fixture = TestBed.createComponent(BuilderComponent);
        const componentInstance = fixture.componentInstance;
        fixture.whenStable().then(() => {
          store.setState(initialState);
          expect(componentInstance['courseBuffer']).toBeDefined();
          expect(componentInstance['courseName']).toBeDefined();
          expect(componentInstance['selectedCourseContentElementUid']).toBeNull();
        });
      });
    });
  });

  afterEach(() => {
    initialState = state;
  });
});

您已创建模拟子组件 - MockBuilderNavbarComponent 并将其包含在声明中。

但是,您还导入了在其声明中包含 BuilderNavbarComponent 的 BuilderNavbarModule。

从导入中删除模块,它应该可以工作。