gpt4 book ai didi

angular - 如何在@ngrx/data 中对 EntityCollectionServiceBase 进行单元测试?

转载 作者:行者123 更新时间:2023-12-04 12:24:18 27 4
gpt4 key购买 nike

我有一个虚拟服务:

export class PatientService extends EntityCollectionServiceBase<Patient> {
constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory) {
super('Patient', serviceElementsFactory);
}
}

我有以下测试:
describe('PatientService', () => {
let service: PatientService;

beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(PatientService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});

它给了我:
NullInjectorError: No provider for EntityCollectionServiceElementsFactory
所以我更新如下:
describe('PatientService', () => {
let service: PatientService;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [EntityDataModuleWithoutEffects.forRoot(entityConfig)],
providers: [provideMockStore()],
});
service = TestBed.inject(PatientService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});

但现在它给了我:
NullInjectorError: No provider for ScannedActionsSubject!
如何正确修复我的测试?

最佳答案

是的,你很亲近,就那样做。您需要在测试台中提供配置所需的一切。

在我们的例子中,这意味着 PatientService应提供作为测试单位和EntityCollectionServiceElementsFactory应作为其依赖项提供。

但是EntityCollectionServiceElementsFactory有自己的依赖项:EntityDispatcherFactory , EntityDefinitionService , EntitySelectorsFactoryEntitySelectors$Factory .我们不想提供,因为它们可能有自己的依赖关系,使我们的生活变得更糟。

要修复它,让我们简单地 sub EntityCollectionServiceElementsFactory .

describe('PatientService', () => {
let service: PatientService;

beforeEach(() => {
TestBed.configureTestingModule({
providers: [
PatientService,
{
provide: EntityCollectionServiceElementsFactory,
// our stub
useValue: {
methodsToFake: jasmine.createSpy(),
// ....
},
},
],
});
service = TestBed.inject(PatientService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});

同样为了避免将来模拟依赖项及其方法的痛苦,您可以使用 ng-mocks .然后测试看起来像这样:

describe('PatientService', () => {
let service: PatientService;

beforeEach(() => {
TestBed.configureTestingModule({
providers: [
PatientService,
{
provide: EntityCollectionServiceElementsFactory,
useValue: MockService(EntityCollectionServiceElementsFactory),
},
],
});
service = TestBed.inject(PatientService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});

关于angular - 如何在@ngrx/data 中对 EntityCollectionServiceBase 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62046207/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com