繁体   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