0

For some Reason this line is failing, but within my logs it shows that the component was initialized with the correct value.

for (let i = 0; i < 20; i++) {
  this['answer_' + (i + 1)] = new FormControl(this.questions[i].answer);

My Jasmine test spec:

 it('should be created', () => {
    let pvqStepUpService: PVQStepUpService = TestBed.get(PVQStepUpService);

    pvqStepUpService.data = pvqstepUpResponse;
    let questions = [];
    questions = pvqStepUpService.data.pvqs;
    let questionsArr = [];
    let answerControlArr = [];

    component.ngOnInit();

    component.answerControlArr = answerControlArr;
    component.questions = questions;
    console.log('TEST COMPONENT ANSWER CONTROL ARR IS ---> ', component.answerControlArr[0]);
    console.log('Test Component: ANSWER ARRAY ---> ', component.questions[0]);
    console.log('TEST component FORMGROUP ---> ', component.pvqForm);
    console.log("TEST ANSWER CONTROL ---> {}", component.answer_1);
    console.log("TEST ANSWER OF QUESTION ---> ", component.questions[0].answer);


    expect(component).toBeTruthy();
  });

enter image description here

I solved it:

Had fixture.detectChanges(); outside of the it block, I placed it just before ngOninit after all my variables were initialized, and it worked.

Taranjit Kang
  • 2,510
  • 3
  • 20
  • 40
  • 1
    You are trying to refer to `question[0]` before you have created the questions it looks like. Could you add the whole `ngOnInit()` method as it is unclear just from that segment – 0mpurdy Jul 30 '17 at 19:28
  • Added the rest of the ngOnInit(), and hey! – Taranjit Kang Jul 30 '17 at 19:43
  • 1
    I find this code very difficult to read because you have so much unnecessary repetition. Is there a reason why you are not using `FormBuilder` to initialise these `FormControl`s as discussed in [this question](https://stackoverflow.com/a/45270475/6894075). I believe the error is because you are trying to access an array value that doesn't exist like the error itself describes but it's very hard to read with this much code – 0mpurdy Jul 30 '17 at 19:56
  • Was not getting the correct result doing so, resorted to my own way. Needed to associate controls + labels together. – Taranjit Kang Jul 30 '17 at 19:59
  • 1
    @TaranjitKang can you show us the part where you call `Testbed.createComponent` and are you sure that the questions array actually has values (log it in the test)? – malifa Jul 30 '17 at 20:19
  • Added screen shot of log as well as full ts code – Taranjit Kang Jul 30 '17 at 20:42
  • Solved it, thanks guys – Taranjit Kang Jul 30 '17 at 23:59

0 Answers0