【问题标题】:TypeError: Cannot read properties of undefined (reading 'and')TypeError:无法读取未定义的属性(读取“和”)
【发布时间】:2021-12-20 09:11:39
【问题描述】:

请帮忙!尝试运行浅层集成测试时出现上述类型错误。

我已经多次查看我的代码以检查我是否有问题,但一切似乎都已到位。

我正在努力让这个测试通过。

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

它在 Karma 中不断出现此错误。

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

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

【问题讨论】:

  • 你没有正确地模拟你的英雄服务。
  • 你是对的。

标签: javascript angular unit-testing testing integration-testing


【解决方案1】:

我不确定您使用的是什么单元测试框架:

你的线路在这里

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

通过该错误,我可以看出编译器正在尝试从对象mockHeroService.getHeroes 中读取属性and。但是mockHeroService.getHeroes 本身是未定义的。所以编译器无法读取and的undefined

问题出在mockHeroService.getHeroes

请检查mockHeroService与茉莉花

【讨论】:

  • 我不认为这是真的,如果节点抛出:Cannot read properties of undefined (reading 'and') 这意味着它本身是未定义的。并不是说它是一个函数而不是一个成员。
  • 这就是我到目前为止所写的关于这个测试的全部内容。当我写这行 mockHeroService = jasmine.createSpyObj(['getHeroes, addHero, deleteHero']); 时,你可以看到我设置了 mockHeroService。
  • 你是对的! mockHeroService 方法中的引号是错误的。
【解决方案2】:

mockHeroService 方法中的引号没有正确放置。

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

应该是这个。

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

【讨论】:

    猜你喜欢
    • 2021-11-26
    • 2021-11-24
    • 2021-11-27
    • 2022-01-21
    • 2021-12-04
    • 2021-12-09
    • 2021-12-06
    • 2022-01-13
    • 2022-01-16
    相关资源
    最近更新 更多