即使正确配置间谍,Angular 单元测试也失败

Angular unit test failing even when configuring correctly spies

提问人:Julio Rodriguez 提问时间:10/31/2023 更新时间:10/31/2023 访问量:18

问:

我的组件如下所示:

  constructor(
    private readonly dialogRef: MatDialogRef<ChangeRolesDialogComponent>,
    private readonly rolesService: RolesService,
    private readonly usersService: UsersService
  ) {}

  ngOnInit(): void {
    this.rolesService.getAllRoles().subscribe((roles: Role[]) => {
      this.roles = roles;
    });
 
  }

在 .spec 文件的配置中,我这样做了:

fdescribe('ChangeRolesDialogComponent', () => {
  let component: ChangeRolesDialogComponent;
  let fixture: ComponentFixture<ChangeRolesDialogComponent>;

  let rolesServiceSpy: jasmine.SpyObj<RolesService>;
  let usersServiceSpy: jasmine.SpyObj<UsersService>;
  let matDialogRefSpy: jasmine.SpyObj<MatDialogRef<ChangeRolesDialogComponent>>;

  beforeEach(async () => {
    rolesServiceSpy = jasmine.createSpyObj('RolesService', ['getAllRoles']);
    usersServiceSpy = jasmine.createSpyObj('UsersService', [
      'getCurrentUserAuthentication',
    ]);

    matDialogRefSpy = jasmine.createSpyObj('MatDialogRef', ['close']);
    await TestBed.configureTestingModule({
      declarations: [ChangeRolesDialogComponent],
      providers: [
        { provide: RolesService, useValue: rolesServiceSpy },
        { provide: UsersService, useValue: usersServiceSpy },
        { provide: MatDialogRef, useValue: matDialogRefSpy },
        { provide: MatDialogRef, useValue: {} },
      ],

这是单元测试:

 it('should get all roles on init', () => {
    const roles: Role[] = [Role.ADMINISTRATORS, Role.PRICING_ADMIN];
    rolesServiceSpy.getAllRoles.and.returnValue(of(roles));

    component.ngOnInit();

    expect(component.roles).toEqual(roles);
  });

但它失败了,并出现错误:

“应该在 init FAILED 上获取所有角色 TypeError:无法读取 undefined 的属性(读取 'subscribe')”

你可以帮我吗?

角度 单元测试 Jasmine Karma-Jasmine

评论


答:

0赞 JFPicard 10/31/2023 #1

该方法必须返回可订阅的可观察对象。getAllRoles

rolesServiceSpy.getAllRoles.and.returnValue(of({}));

您可以将 更改为已定义的对象的实际值of({})Role