Angular 无法读取未定义错误的属性订阅

普拉维什·谢蒂

我得到了这个奇怪的无法读取未定义错误的订阅,奇怪的是当它独立运行时不会出现某些东西,但在不使用集中测试的情况下运行时几乎所有时间都会出现

错误现在显示在view-access-group.component.ts文件中的this.accessGroupService.getAccessGroup(accessGroupId).subscribe( (json) 行

这是测试文件

view-access-group.component.spec.ts

describe("ViewAccessGroupComponent", () => {
  let component: ViewAccessGroupComponent;
  let fixture: ComponentFixture<ViewAccessGroupComponent>;
  let notifyServiceSpy: jasmine.SpyObj<NotificationService>;
  let accessGroupSpy: jasmine.SpyObj<AccessGroupService>;
  let route:ActivatedRoute;

  let activatedRouteMock = {
    params: of({ id: 1 })
  }
  

let g1: AccessGroup = {
    id: 1,
    active: true,
    display_name: '',
    description: '',
    access_group_features: [],
    toJSON: null
  }

  beforeEach(async(() => {
    const notifyServiceSpyObj = jasmine.createSpyObj("NotificationService", [
      "show",
    ]);
    const accessGroupServiceSpyObj = jasmine.createSpyObj(
      "AccessGroupService",[
        "getAccessGroup"
      ]
    );

    TestBed.configureTestingModule({
      imports: [
        ConfigurationModule,
        HttpClientTestingModule,
        RouterTestingModule,
      ],
      providers: [
        TranslateService,
        TranslateStore,
        Globals,
        { provide: NotificationService, useValue: notifyServiceSpyObj },
        { provide: AccessGroupService, useValue: accessGroupServiceSpyObj },
        {provide:ActivatedRoute,useValue:activatedRouteMock}
      ],
    }).compileComponents();
    notifyServiceSpy = TestBed.get(NotificationService);
    accessGroupSpy=TestBed.get(AccessGroupService);
    route=TestBed.get(ActivatedRoute)
  }));

  afterEach(()=>{
    fixture.destroy();
  });

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

  it("should create", () => {
    expect(component).toBeTruthy();
  });

  it("#getAccessGroup should show error message if API fails ", () => {

    accessGroupSpy.getAccessGroup.and.returnValue(throwError({error:{message:"error"}}))
    
    component.getAccessGroup(1);

    expect(notifyServiceSpy.show).toHaveBeenCalledWith("error", {
      position: "top",
      duration: "3000",
      type: "error",
    });
  });

  it('when params has id', () => {

    accessGroupSpy.getAccessGroup.and.returnValue(of(g1))

    TestBed.createComponent(ViewAccessGroupComponent)

    expect(component.accessGroupId).toBe(1)
  })
});

这是主要的打字稿文件:

view-access-group.component.ts

@Component({
  selector: "batavia-view-access-group",
  templateUrl: "./view-access-group.component.html",
  styleUrls: ["./view-access-group.component.scss"],
})
export class ViewAccessGroupComponent implements OnInit {
  accessGroup: AccessGroup = new AccessGroup();
  accessGroupId: number;
  user: User;
  isLoading = false;
  accessGroupFeatures: AccessGroupFeature[];

  constructor(
    private accessGroupService: AccessGroupService,
    private activatedRoute: ActivatedRoute,
    private globals: Globals,
    private _notify: NotificationService,
    private translate: TranslateService
  ) {
    this.activatedRoute.params.subscribe((params: Params) => {
      if (params.id) {
        this.accessGroupId = params.id;
        this.getAccessGroup(params.id);
      }
    });

    this.globals.userObservable.subscribe((user) => (this.user = user));
  }

  ngOnInit() {}

  getAccessGroup(accessGroupId: number) {
    this.isLoading = true;
    this.accessGroupService.getAccessGroup(accessGroupId).subscribe(
      (json) => {
        this.isLoading = false;
        this.accessGroup = json;
      },
      (error) => {
        this.isLoading = false;
        const errMsg = this.translate.instant(
          "ACCESS_GROUPS.ERROR_FETCHING_ROLES"
        );
        this._notify.show(
          error.error && error.error.message ? error.error.message : errMsg,
          {
            position: "top",
            duration: "3000",
            type: "error",
          }
        );
      }
    );
  }
}

我不知道为什么我会收到这个错误。我尝试了很多网站上提到的东西,比如添加一个 afterEach 循环。

有人可以指出为什么我的代码出错

曼哈顿先生

在到达测试用例之前调用您的 spy:

beforeEach(() => {
    fixture = TestBed.createComponent(ViewAccessGroupComponent);  // HERE, the constructor is called
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

您可以将订阅移动到ngOnInit,然后订阅将在fixture.detectChanges()调用时完成,因此您可以在设置间谍结果的下方移动该调用:

  it("#getAccessGroup should show error message if API fails ", () => {

    accessGroupSpy.getAccessGroup.and.returnValue(throwError({error:{message:"error"}}))
    
    fixture.detectChanges(); // HERE instead of in beforeEach

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

无法在 Angular 中读取未定义的属性(读取“订阅”)

Angular - TypeError:无法读取未定义的属性“订阅”

Angular - Ionic 2 - 无法读取未定义的属性“订阅”

单元测试 Angular 4 出现错误“TypeError:无法读取未定义的属性“订阅”

无法读取Angular 2中未定义的属性“错误”?

Angular CLI 错误无法读取未定义的属性“写入”

Angular Material sidenav错误:无法读取未定义的属性

错误:无法读取未定义Angular 5的属性'cloneDeep'

Angular @ViewChild错误'无法读取未定义的属性nativeElement”

类型错误:无法读取未定义的 Angular 的属性“提交”

Angular SSR - 无法读取未定义的属性(读取“取消订阅”)

Angular SSR - 无法读取未定义的属性(读取“取消订阅”)

Angular无法读取未定义的属性

无法读取未定义 Angular 的属性

Angular2可观察到的问题,无法读取未定义的属性“订阅”

Angular2 / 4-无法读取未定义的属性订阅

Angular Component 测试 TypeError:无法读取未定义的属性“订阅”

Angular - 错误类型错误:无法读取未定义的属性(读取“vehicle_image”)

错误类型错误:无法在 Angular 中读取未定义的属性(读取“removeVietnameseTones”)

无法读取未定义读取“deletePostById”Angular 的属性

无法读取未定义的属性(读取“updateLicence”)Ionic Angular

Angular 2:错误类型错误:无法读取未定义的属性“值”

Angular - core.js:6210 错误类型错误:无法读取未定义的属性“角色”

Angular 6 错误类型错误:无法读取未定义的属性“导航”

错误类型错误:无法读取 Angular 4 中未定义的属性“setupScene”

Angular 7-错误错误:未捕获(承诺):TypeError:无法读取未定义的属性“ forEach”

Angular Production构建错误“无法读取未定义的属性'toLowerCase'中的错误”

Angular 6 中的“错误类型错误:无法读取未定义的属性‘名称’”

错误类型错误:无法读取未定义的属性“ID”(Angular 8)