Ошибка Karma TypeError, вызванная вводом углового компонента без типов - PullRequest
0 голосов
/ 08 марта 2019

Я получаю эту ошибку:

TypeError: Cannot read property 'url' of undefined

Причина в этом разделе кода:

    export class ImageCardComponent implements OnInit {
        @Input() image: any; // Can be an image or imageToUpload
        imageUrls = [];


...    

    ngOnInit() {
            this.imageUrls.push((this.image as any).url);
            this.image.outOfSync = true;
        }

тестовый код

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ImageCardComponent ],
      imports: [FormsModule],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ImageCardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    component.image = getImageGetResponseMock().image;
  });

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

фиктивные данные

export function getImageGetResponseMock() {
    return {
        id: 1,
        image: [
            {
                id: 2,
                height: 90,
                width: 160,
                format: 'jpg',
                url: 'https://i.imgflip.com/mlqo9.jpg?a430032',
                tags: ['testTag']
            }
        ]
    };
}

Как я могу исправить это? Нужно ли мне объединить два моих возможных ввода в общий класс или есть способ предоставить тестовый сценарий макет ввода?

1 Ответ

1 голос
/ 08 марта 2019

imageUrl не инициализируется значением, которое означает, что оно будет неопределенным, если вы попытаетесь получить значение из него до того, как оно получит значение.

Вы должны высмеивать объекты, необходимые в ваших тестах, изатем запишите свои тестовые случаи.

const imageUrl = {image: 'testImage.png', url:'image_url'};

Now После настройки TestBed, имейте блок beforeEach для макета необходимых входных данных:

beforeEach(() => {
  const fixture = TestBed.createComponent(ImageCardComponent );
  component = fixture.componentInstance;
  component.imageUrl= imageUrl;
});

it('should have image url info', () => {
  expect(component.imageUrl).toBeTruthy(); // whatever you have to check for..
)};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...