Angular Karma/Jasmine 单元测试无法读取未定义的 Readin imageUrl 的属性

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

我在单元测试中已经解决了几天的错误。到目前为止,我的研究所尝试的一切似乎都没有解决问题。我的三个组件未能通过单元测试,并出现相同的错误无法读取未定义的读取 imageUrl 的属性,这是我的模型的属性。 该错误来自我的模板。我所做的一些研究表明,必须在测试台中提及此属性,根据我读到的内容,这对我不起作用。由于此错误,我的组件没有被创建。我注释掉了一些测试,直到解决此错误。 有人可以告诉我我做错了什么或指出我正确的方向。这将不胜感激。 包含代码片段。

型号产品.ts

export class Product {
_id:string;
name: string;
size: string;
description: string;
price: number;
imageUrl: string;
static price: Product;

  constructor(_id:string, name: string, description="", size:string, price=0, 
  imageUrl="" 

  ){

    this._id=_id;
    this.name = name;
    this.description = description;
    this.price= price;
    this.size= size;
    this.imageUrl = imageUrl;
   }

 }

 

产品-item.component.html

 <img class=" img-fluid shacker"  [src]="productItem.imageUrl" alt="Clothing" />

产品项目.组件.规格.ts

  import { ComponentFixture, TestBed, async } from '@angular/core/testing';
  import { WishlistItemService } from '@app/services/wishlist-item.service';
  import { CartService } from '@app/services/cart.service';
  import { HttpClientTestingModule } from '@angular/common/http/testing';
  import { ProductItemComponent } from './product-item.component';
  import { RouterTestingModule } from '@angular/router/testing';
  import { AlertComponent } from '@app/_components';
  import { Product } from '@app/models/product';


 const FAKE_PRODUCTS:Product[] = 
 [
{
  "_id": "0001",
  "name": "Black One Piece",
  "size": "M",
  "description": "Lorem Ipsum is simply dummy text of the printing and typesetting 
   industry. Lorem Ipsum has been the industry's standard dummy text ever since the 
   1500s, when an unknown printer took a galley of type and scrambled it to make a type 
   specimen book.",
  "imageUrl": "http://localhost:4200/assets/BlacknwhiteOne.png",
  "price": 199
 },
 {
  "_id": "00002",
  "name": "Overalls",
  "size": "M",
  "description": "Lorem Ipsum is simply dummy text of the printing and typesetting 
   industry. Lorem Ipsum has been the industry's standard dummy text ever since the 
   1500s, when an unknown printer took a galley of type and scrambled it to make a type 
   specimen book.",
  "imageUrl": "http://localhost:4200/assets/overalls.png",
  "price": 250, 

  }

]

  const okResponse = new Response(JSON.stringify(FAKE_PRODUCTS), {
  status: 200,
  statusText: 'OK'
});





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

  beforeEach(async () => {

  const wishlistitemServiceSpy = jasmine.createSpyObj<WishlistItemService> 
  (['addProductItemToWishlistItem']);
  const cartServiceSpy = jasmine.createSpyObj<CartService>(['addAllproducts']);
  //const cartServiceSpy= jasmine.createSpy('fetch').and.returnValue(okResponse);
  //cartServiceSpy.addProductToCart.and.returnValue([FAKE_PRODUCTS]) 


  await TestBed.configureTestingModule({
  declarations: [ ProductItemComponent, AlertComponent ],
  imports:[HttpClientTestingModule, RouterTestingModule],
  providers:[
    {
      WishlistItemService, useValue: wishlistitemServiceSpy,
      CartService, uses: cartServiceSpy
    }
  ]

 })
   .compileComponents();
});

  beforeEach(() => {
  fixture = TestBed.createComponent(ProductItemComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();   
});

  it('should create', () => {
  component.imageUrl  //this is where I'm having trouble it needs to be mentioned not sure how  
  expect(component).toBeTruthy();
 });


});

这里是product-item.component.ts的片段:

   export class ProductItemComponent implements OnInit {


      [x: string]: any;

      form!: UntypedFormGroup; 
      submitted=false;
      sizeBy!: string;

     Valuesize!: string;
     size!: string;
     imageUrl!: string



//products is my database collection
//Products is my model/interface for db 
  products:Products[] = [];

 cartItems: CartItem[] = [];
 @Input() cartItem!: CartItem;


@Input() productItem!: Product; 



ngOnInit() {
    this.form = this.formBuilder.group({
     sizeBy: ['', Validators.required]
});
   

}
angular unit-testing karma-runner
1个回答
0
投票

问题是,在您的组件中,您期望定义输入

productItem
,如使用明确赋值断言
!
所示。但是,在单元测试中,您没有定义输入。要修复它,请在测试中设置输入:

beforeEach(() => {
  fixture = TestBed.createComponent(ProductItemComponent);
  component = fixture.componentInstance;
  component.componentRef.setInput('productItem', FAKE_PRODUCTS[0]);
  fixture.detectChanges();   
});

或者,您可以删除

!
运算符并修复生成的类型错误,以便组件可以处理未定义的
productItem

© www.soinside.com 2019 - 2024. All rights reserved.