[英]Angular tests - NullInjectorError: StaticInjectorError(DynamicTestModule)[NgxPermissionsDirective -> NgxPermissionsService]
[英]Angular test NullInjectorError: StaticInjectorError(DynamicTestModule)[UsersEffects -> Actions]:
我正在使用 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([]),
我可能会错过什么?
下面的代码解决了 NullInjectorError: No provider for Actions: 在我的组件中:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Actions } from '@ngrx/effects';
import { provideMockActions } from '@ngrx/effects/testing';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
import { YourComponent } from './your.component';
describe('YourComponent ', () => {
let component: YourComponent ;
let fixture: ComponentFixture<YourComponent>;
let store: MockStore;
let actions: Actions;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [YourComponent ],
providers: [
provideMockStore(),
provideMockActions(() => actions)
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(YourComponent );
component = fixture.componentInstance;
store = TestBed.inject(MockStore);
actions = TestBed.inject(Actions);
fixture.detectChanges();
});
it('should create YourComponent ', () => {
expect(component).toBeTruthy();
});
});
在您的测试中,您应该使用 NGRX 提供的 Mock 元素:
let store: MockStore<any>
...
TestBed.configureTestingModule({
providers: [
...,
provideMockStore()
]
})
...
store = TestBed.get(Store)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.