typescript - Vấn đề phụ thuộc vòng tròn Angular trong các bài kiểm tra đơn vị Jest
Tôi có các thành phần Angular sau. Chúng biên dịch và chạy tốt trong ứng dụng của tôi. Tuy nhiên, khi tôi đưa module vào kiểm tra bằng Jest, tôi gặp lỗi. Tôi không biết vấn đề là do cấu hình TypeScript, Angular, Jest hay sự kết hợp của chúng.
Các thành phần :
@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 { }
Như bạn có thể thấy, có một sự phụ thuộc tuần hoàn. Tuy nhiên, nó nên được sửa bằng @Inject(forwardRef(() => ParentComponent)) nhưng điều này không hoạt động.
thông số :
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 { }
Và tôi nhận được lỗi sau khi chạy bài kiểm tra đơn vị của mình.
ReferenceError: ParentComponent is not definedTôi muốn thêm rằng nếu tôi làm tương tự với Jasmine/Karma, tôi không gặp lỗi này.
Câu trả lời #1
Khi tôi tách hai thành phần này thành các tệp riêng biệt, vấn đề đã được giải quyết.
Câu trả lời #2
Hãy thử sử dụng trong các bài kiểm tra của bạn
const el = fixture.debugElement.nativeElement;
expect(el.outerHTML).toMatchSnapshot();
Nếu bạn nâng cấp lên phiên bản Angular mới nhất (hiện tại là 5.2.9), những bài kiểm tra này sẽ chạy hết bộ nhớ!
