簡體   English   中英

如何在角度單元測試中模擬 ControlContainer?

[英]How to mock ControlContainer in angular unit test?

如何模擬ControlContainer實例以便我可以測試我的組件?

我有一個將ControlContainer注入構造函數的子組件,所以它的用法是

<acr-score-card formGroupName="score"></acr-score-card>

組件本身是

@Component({
  selector: 'acr-score-card',
  templateUrl: './score-card.component.html',
  styleUrls: ['./score-card.component.scss']
})
export class ScoreCardComponent implements OnInit {

  ...

  form: FormGroup;

  constructor(private ngControl: ControlContainer) { }

  ngOnInit() {
    this.form = <FormGroup>this.ngControl.control;
  }

  ...

}

當我在瀏覽器中運行時,一切正常,但我無法使單元測試正常工作,因為我不確定如何模擬ControlContainer實例以設置提供程序,這是我的規范文件的內容:

describe('ScoreCardComponent', () => {
  let component: ScoreCardComponent;
  let fixture: ComponentFixture<ScoreCardComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [TestingModule],
      declarations: [ScoreCardComponent],
      providers: [/** what goes here to mock the ControlContainer */]
      schemas: [NO_ERRORS_SCHEMA]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ScoreCardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

所以,重復這個問題,我如何模擬ControlContainer實例以便我可以測試我的組件?

感謝@KiraAG 的評論,並且能夠從提供的鏈接中找出所需的內容,因此請在此處發布答案,以防其他人遇到此問題

因此,在您的測試中,您需要在測試模塊中provide ControlContainer實例,這基本上是FormGroupDirectiveFormControlDirective具體取決於您希望傳遞給組件的內容。

例如,在您的測試文件中創建代表您正在使用的表單部分的FormGroup

const fg: FormGroup = new FormGroup({
  'answer': new FormControl(''),
  ...
});

接下來創建一個FormGroupDirective並將form屬性設置為FormGroup創建的FormGroup

const fgd: FormGroupDirective = new FormGroupDirective([], []);
fgd.form = fg;

現在在您測試模塊設置中,您可以提供ControlContainer

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [TestingModule],
      declarations: [ScoreCardComponent],
      providers: [
        { provide: ControlContainer, useValue: fgd }
      ]
      schemas: [NO_ERRORS_SCHEMA]
    })
      .compileComponents();
  }));

就是這樣,構造函數注入得到滿足。

我使用了尼爾史蒂文斯的回答。

但我有

viewProviders: [{provide: ControlContainer, useExisting: FormGroupDirective}],

在組件中。

所以在測試中我必須使用

providers: [{provide: FormGroupDirective, useValue: fgd}],

也許這會幫助某人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM