向 Angular 独立组件测试提供模拟 NGRX 存储的正确方法是什么?

问题描述 投票:0回答:1

我不知道如何为 Angular 中的独立组件测试导入/提供模拟商店。为非独立组件测试提供模拟商店是通过

provideMockStore()
完成的,但这似乎不适用于独立组件。

示例组件和测试
@Component({
  standalone: true,
  imports: [
    CommonModule,
    FeatureStoreModule, // Import feature store module to access selectors/actions
  ],
  selector: 'standalone',
  templateUrl: './standalone.component.html',
  styleUrls: ['./standalone.component.scss'],
})
export class StandaloneComponent {
  constructor(private store: Store) {}

  dispatchAction(): void {
    this.store.dispatch(featureStoreAction()); // Dispatch action imported from FeatureStoreModule
  }
}

describe('StandaloneComponent', () => {
  let component: StandaloneComponent;
  let fixture: ComponentFixture<StandaloneComponent>;
  let store: MockStore;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [StandaloneComponent],
      providers: [provideMockStore()], // Provide a mocked store for component
    }).compileComponents();

    store = TestBed.inject(MockStore);

    fixture = TestBed.createComponent(StandaloneComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
已安装的软件包
"@angular/core": "16.2.4",
"@ngrx/effects": "16.0.1",
"@ngrx/entity": "16.0.1",
"@ngrx/router-store": "16.0.1",
"@ngrx/store": "16.0.1",
"jest": "29.4.3",
"jest-preset-angular": "13.1.1",
问题

运行此测试会引发错误:

NullInjectorError: NullInjectorError: No provider for _StoreRootModule!

angular unit-testing jestjs ngrx
1个回答
0
投票

最有可能的是,对于用于测试的独立组件,我们必须利用

overrideComponent

你可以尝试以下方法看看它是否有效(用!!来评论)?

describe('StandaloneComponent', () => {
  let component: StandaloneComponent;
  let fixture: ComponentFixture<StandaloneComponent>;
  let store: MockStore;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [StandaloneComponent],
      providers: [provideMockStore()], // Provide a mocked store for component
    })
    // !! Add overrideComponent here
    .overrideComponent({
      // !! set the providers.
      set: {
        providers: [provideMockStore()]
      },
      // !! Remove the feature store module
      remove: {
        imports: [FeatureStoreModule]
      }
    })
    .compileComponents();
    
    // !! Not sure if the below line will work.
    // store = TestBed.inject(MockStore);
    

    // !! Try getting the store like this, from the component first
    // before going to the root injector
    store = fixture.debugElement.injector.get(MockStore);
    fixture = TestBed.createComponent(StandaloneComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.