Tyler B. Joudrey
Tyler B. Joudrey

Reputation: 491

Karma TypeError caused by a typeless angular component input

I am receiving this error:

TypeError: Cannot read property 'url' of undefined

Cause by this section of code:

    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;
        }

test code

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();
  });
});

mock data

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']
            }
        ]
    };
}

How can I go about fixing this? Do I need to consolidate my two possible inputs into a common class or is there a way to provide the test script a mock of an input?

Upvotes: 0

Views: 26

Answers (1)

nircraft
nircraft

Reputation: 8478

imageUrl is not initialized with a value that means it will be undefined if you try to get a value from it before it has a value.

You should be mocking the objects needed in your tests and then write your test cases.

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

Now After TestBed set up, have a beforeEach block to mock the needed inputs:

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..
)};

Upvotes: 1

Related Questions