gpt4 book ai didi

angular - 如何在单元测试中模拟 ApplicationRef

转载 作者:行者123 更新时间:2023-12-03 21:26:02 28 4
gpt4 key购买 nike

我试图通过 Jasmine 和 Angular 4 测试这两种方法,但是 this.applicationRef总是返回一个空对象。这个怎么解决?

这是我的代码:

@Injectable()
class Dialog {
....
getRootViewContainerRef(): ViewContainerRef {
const appInstance = this.applicationRef.components[0].instance;

if (!appInstance.viewContainerRef) {
const appName = this.applicationRef.componentTypes[0].name;
throw new Error(`Missing 'viewContainerRef' declaration in ${appName} constructor`);
}

return appInstance.viewContainerRef;
}
}

createOverlay(parentContainerRef: ViewContainerRef): ComponentRef<DialogContainerComponent> {
const rootContainerRef = parentContainerRef;
const rootInjector = rootContainerRef.injector;

const bindings = ReflectiveInjector.resolve([]);
const injector = ReflectiveInjector.fromResolvedProviders(bindings, rootInjector);

const overlayFactory = this.cfr.resolveComponentFactory(DialogContainerComponent);
return rootContainerRef.createComponent(overlayFactory, rootContainerRef.length, injector);
}

这是我的测试脚本:

describe('Dialog service', () => {
//let fixture: ComponentFixture<DialogInformationComponent>;
//let component: DialogInformationComponent;

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [...],
providers: [
{provide: APP_BASE_HREF, useValue: '/'},
Dialog, DialogContext
]
});
}));

it('Dialog should be showed.', inject([Dialog], (service: Dialog) => {
let res: any;
service.open(DialogInformationComponent, message).subscribe((result) => {
res = result;
});
expected(true).toBeTruethy();
}));
});

然而, ApplicationRef总是空的:

enter image description here

最佳答案

我通过创建一个新的 MockComponent 来解决,然后将其推送到当前的 TedBed ApplicationRef 中,如下所示:

 @Component({
selector: 'app-dialog',
template: ''
})
class MockDialogComponent {
constructor(public viewContainerRef: ViewContainerRef) {
}
}

@NgModule({
imports: [DialogModule],
declarations: [MockDialogComponent]
})
class MockDialogModule {
}

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [CommonModule, MockDialogModule]
});
}));

beforeEach(() => {
appRef = TestBed.get(ApplicationRef) as ApplicationRef;
fixture = TestBed.createComponent(MockDialogComponent);
appRef.components.push(fixture.componentRef);
de = fixture.debugElement;
fixture.detectChanges();
});

it('Dialog should be showed.', inject([Dialog], (service: Dialog) => {
service.open(DialogInformationComponent, message).subscribe();
fixture.detectChanges();
expect(service.isShow).toBe(true);
}))

关于angular - 如何在单元测试中模拟 ApplicationRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46893227/

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