角度测试:无法读取未定义的属性'images'>>

问题描述 投票:0回答:1

我正在尝试在名为AlbumInfoComponent的Angular组件上运行业力测试。在此组件中,我有一个名为getStyles()的函数,该函数执行以下操作:

  getStyles() {
    return {
      "background-image":'url('+this.data.images[1].url+')'
    }
  }

它使用名为data的变量,其初始化为:private user: {} = {}

我有一个仅运行默认should create测试的测试。尽管由于某种原因在运行测试时得到TypeError: Cannot read property 'images' of undefined。我最初的想法是,由于Angular不知道数据中存在名为images的值,因此它将失败。因此,我尝试将组件设置为等于模拟组件数据。这是我的测试代码:

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LandingComponent, FaIconComponent, HomeComponent, LoginComponent, AlbumInfoComponent, RecentReleasesComponent, QueueComponent, SearchComponent, TitleComponent, UserComponent, SearchBarComponent, RecentReleaseComponent, YourQueueComponent    ],
      imports: [FormsModule, HttpClientTestingModule,         RouterTestingModule.withRoutes([]), MatSnackBarModule    ],
      providers: [InfoService, HttpClient, TokenService ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AlbumInfoComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  it('should create', () => {    
    component.data = {
      "images": [
      {
        "height": 640,
        "url": "https://i.scdn.co/image/ab67616d0000b273626d2ce1fb80955645d4d787",
        "width": 640
      },
      {
        "height": 300,
        "url": "https://i.scdn.co/image/ab67616d00001e02626d2ce1fb80955645d4d787",
        "width": 300
      },
      {
        "height": 64,
        "url": "https://i.scdn.co/image/ab67616d00004851626d2ce1fb80955645d4d787",
        "width": 64
      }
      ]
    }
    expect(component).toBeTruthy();
  });
});

是否有一种方法可以迫使数据变量等于模拟数据来纠正错误?

我正在尝试在名为AlbumInfoComponent的Angular组件上运行业力测试。在此组件中,我有一个名为getStyles()的函数,该函数执行以下操作:getStyles(){return {“ ...

angular unit-testing testing jasmine karma-runner
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.