[英]Angular Circular Dependency issue in Jest unit tests
我有以下角度組件。 他們在我的應用程序中編譯並運行良好。 但是,當我在我的Jest測試中包含該模塊時,我會收到錯誤。 我不知道這是打字稿配置,Angular,Jest還是組合的問題。
組件:
@Component({
selector: 'child-component',
template: '<div>Child here.</div>'
})
export class ChildComponent {
constructor( @Inject(forwardRef(() => ParentComponent)) private
parentComponent: ParentComponent ) { }
}
@Component({
selector: 'parent-component',
template: '<div>
<child-component></child-component>
<child-component></child-component>
</div>'
})
export class ParentComponent{
@ViewChildren(ChildComponent) _children: QueryList<ChildComponent>;
}
const EXPORTED_DECLARATIONS = [
ChildComponent,
ParentComponent
];
@NgModule({
exports: [EXPORTED_DECLARATIONS],
declarations: [EXPORTED_DECLARATIONS]
})
export class TestingModule { }
如您所見,存在循環依賴。 但是,應該使用@Inject(forwardRef(() => ParentComponent))
修復它,但這不起作用。
規格:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TestingModule } from './test';
import { Component, forwardRef } from '@angular/core';
describe( 'TestComponent', () => {
let component: TestTestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ TestComponent ],
imports: [
TestingModule
]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
} );
it( 'default', () => {
expect( fixture ).toMatchSnapshot();
});
});
@Component({
selector: 'test-test-1234',
template: `<parent-component></parent-component>`
})
class TestComponent { }
當我運行單元測試時出現以下錯誤。
ReferenceError: ParentComponent is not defined
我想補充一點,如果我對Jasmine / Karma做同樣的事情,我不會得到這個錯誤。
當我將這兩個組件分成不同的文件時,問題就解決了。
嘗試在測試中使用
const el = fixture.debugElement.nativeElement;
expect(el.outerHTML).toMatchSnapshot();
如果你將升級到最新版本的角度(現在是5.2.9),這些測試將耗盡內存!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.