角度测试NullInjectorError:StaticInjectorError(DynamicTestModule)[UsersEffects-> Actions]:

时间:2019-11-12 11:05:25

标签: angular jasmine ngrx

我正在使用Angular Jasmine编写uit测试。我收到以下错误:

  

NullInjectorError:   StaticInjectorError(DynamicTestModule)[UsersEffects-> Actions]:             StaticInjectorError(平台:核心)[UsersEffects-> Actions]:               NullInjectorError:没有操作提供者!

我的spec.ts文件是:

describe('UsersComponent', () => {
  let component: UsersComponent;
  let fixture: ComponentFixture<UsersComponent>;
  let dialogSpy: jasmine.Spy;
  let dialogRefSpyObj = jasmine.createSpyObj({ afterClosed : of({}), close: null });
  dialogRefSpyObj.componentInstance = { body: '' };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        MaterialModule,
        SharedModule,
        ReactiveFormsModule,
        StoreModule.forRoot({}),
        StoreModule.forFeature('Users', reducer),
        HttpClientModule,
        UnitTestModule,
        BrowserAnimationsModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useClass: DummyTranslateLoader,
          },
        }),
      ],
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [],
      providers: [Store, UsersService],
    })
    .compileComponents();
  }));

  afterEach(() => {
    TestBed.resetTestingModule();
  });

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

  beforeEach(() => {
    dialogSpy = spyOn(TestBed.get(MatDialog), 'open').and.returnValue(dialogRefSpyObj);
  });

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

我还添加了这是app.module.ts:

StoreModule.forRoot({}),
EffectsModule.forRoot([]),

我可能会缺少什么?

1 个答案:

答案 0 :(得分:0)

在测试中,应使用NGRX提供的Mock元素:

let store: MockStore<any>

...

TestBed.configureTestingModule({
   providers: [
   ...,
   provideMockStore()
   ]
})

...

store = TestBed.get(Store)