Angular - mock component - Cannot read properties of undefined (reading 'control')

Viewed 39

I found component similiar to this:

import {Component, Input} from '@angular/core';
import {NgControl, ValidationErrors} from '@angular/forms';


@Component({
  selector: '[bla-bla]',
  template: `{{errors}}`,
})
export class FormComponent {
  @Input('bla-bla') control!: { ngControl: NgControl };

  get errors(): ValidationErrors | null | undefined {
    return undefined.error; // return is simplified here
  }

}

When i wrote test i get an error:

TypeError: Cannot read properties of undefined (reading 'control')
(...)
Error: Expected undefined to be truthy.

My test:

describe('Testing FormComponent', () => {
  let cmp: FormComponent;
  let fixture: ComponentFixture<FormComponent>;
  let mockNgControl;

  beforeEach(() => {
    mockNgControl = jasmine.createSpyObj(
      'ngControl',
      ['errors'],
       { control: null }
    );
    TestBed.configureTestingModule({
      declarations: [ FormComponent, FormControlErrorPipe ],
      providers: [
        { provide: FORM_ERRORS_DICTIONARY, useValue: {} },
      ],
      schemas: [NO_ERRORS_SCHEMA],
    });

    fixture = TestBed.createComponent(FormComponent);
    fixture.componentInstance.control = mockNgControl;
    fixture.detectChanges();
    cmp = fixture.componentInstance;
});

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

Depedencies:

  "dependencies": {
    "@angular/animations": "~11.0.1",
    "@angular/common": "~11.0.1",
    "@angular/compiler": "~11.0.1",
    "@angular/core": "~11.0.1",
    "@angular/forms": "~11.0.1",
    "@angular/platform-browser": "~11.0.1",
    "@angular/platform-browser-dynamic": "~11.0.1",
    "@angular/router": "~11.0.1",
    "rxjs": "~6.6.0",
    "tslib": "^2.0.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.1100.7",
    "@angular/cli": "~11.0.2",
    "@angular/compiler-cli": "~11.0.1",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^12.11.1",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~5.1.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-coverage-istanbul-reporter": "^3.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "karma-junit-reporter": "^2.0.1",
    "karma-sabarivka-reporter": "~3.3.1",
    "karma-spec-reporter": "^0.0.34",
    "karma-viewport": "~1.0.9",
    "ng-packagr": "~11.0.0",
    "nyc": "~15.1.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.0.2"
  }

Why do i get an error in this test? What should i do in this test to stop getting an error ?

0 Answers
Related