簡體   English   中英

類型錯誤:無法讀取未定義的屬性(讀取“和”)

[英]TypeError: Cannot read properties of undefined (reading 'and')

請幫忙! 嘗試運行淺集成測試時,我得到了上面的類型錯誤。

我多次查看我的代碼以檢查我是否有問題,但一切似乎都已就位。

我正在努力讓這個測試通過。

expect(fixture.componentInstance.heroes.length).toBe(3)

它在 Karma 中因此錯誤而不斷失敗。

類型錯誤:無法讀取未定義的屬性(讀取“和”)

import { ComponentFixture, TestBed } from "@angular/core/testing"
import { of } from "rxjs";
import { HeroService } from "../hero.service";
import { HeroesComponent } from "./heroes.component"

describe('HeroesComponent (shallow tests)', () => {
  let fixture: ComponentFixture<HeroesComponent>;
  let mockHeroService;
  let HEROES;  

  beforeEach(() =>{
    HEROES = [
      {id:1, name: 'SpiderDude', strength: 8},
      {id:2, name: 'Wonderful Woman', strength: 24},
      {id:3, name: 'SuperDude', strength: 55}
    ];
    mockHeroService = jasmine.createSpyObj(['getHeroes, addHero, deleteHero']);
    TestBed.configureTestingModule({
      declarations: [HeroesComponent],
      providers: [
        { provide: HeroService, useValue: mockHeroService}
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    fixture = TestBed.createComponent(HeroesComponent)
  })

  it('should set heroes correctly from the service', () => {
    mockHeroService.getHeroes.and.returnValue(of(HEROES))
    fixture.detectChanges();

    expect(fixture.componentInstance.heroes.length).toBe(3)
  });
});

我不確定您使用的是什么單元測試框架:

你的線路在這里

 mockHeroService.getHeroes.and.returnValue(of(HEROES))

通過錯誤,我可以看出編譯器正在嘗試讀取屬性and對象mockHeroService.getHeroes and()應該是一個斷言的函數

它應該是:

 mockHeroService.getHeroes.and().returnValue(of(HEROES))

mockHeroService 方法中的引號未正確放置。

mockHeroService = jasmine.createSpyObj(['getHeroes, addHero, deleteHero']);

應該是這個。

mockHeroService = jasmine.createSpyObj(['getHeroes', 'addHero', 'deleteHero']);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM