无法读取单元测试 NgOnInIt 中未定义的属性(读取“订阅”)

发布于 2025-01-13 05:53:25 字数 1886 浏览 5 评论 0原文

我尝试了很多SO问题的答案,但没有任何效果。所以在mt测试中我做了这样的事情。

const stubStudentService = jasmine.createSpyObj('StudentsCrudService',['getAllStudents','updateStudent']);
const stubWebSocketService = jasmine.createSpyObj('WebsocketService',['getNotified']);

describe('StudentsListComponent', () => {
  let component: StudentsListComponent;
  let fixture: ComponentFixture<StudentsListComponent>;;
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [StudentsListComponent],
      imports: [],
      providers: [
        { provide: StudentsCrudService, useValue: stubStudentService },
        { provide: WebsocketService, useValue: stubWebSocketService },
        NotificationService,
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(StudentsListComponent);
    stubStudentService.getAllStudents.and.returnValue(of(studentPayload));
    stubWebSocketService.getNotified.and.returnValue(of('success'));
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

在我的组件中,它看起来像这样

  constructor(
    private studentService: StudentsCrudService,
    private notificationService: NotificationService,
    private webSocketNotifier: WebsocketService
  ) {}

  ngOnInit(): void {
    this.studentSubscription();
    this.webSocketSubscription();
  }

  studentSubscription() {
    this.studentQueryRef =  this.studentService
    .getAllStudents()
    this.initSubscription.add(
      this.studentQueryRef
        .valueChanges.subscribe((response) => {
          this.paginatedStudents = {...response.data.paginateStudents}
        })
    );
  }

当我运行测试时,我得到无法读取StudentsListComponent.studentSubscription中未定义的属性(读取“订阅”)。我尝试了很多事情但没有任何效果。

I tried a lot of SO Question's answers but nothing worked for this.so in mt test im doing something like this.

const stubStudentService = jasmine.createSpyObj('StudentsCrudService',['getAllStudents','updateStudent']);
const stubWebSocketService = jasmine.createSpyObj('WebsocketService',['getNotified']);

describe('StudentsListComponent', () => {
  let component: StudentsListComponent;
  let fixture: ComponentFixture<StudentsListComponent>;;
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [StudentsListComponent],
      imports: [],
      providers: [
        { provide: StudentsCrudService, useValue: stubStudentService },
        { provide: WebsocketService, useValue: stubWebSocketService },
        NotificationService,
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(StudentsListComponent);
    stubStudentService.getAllStudents.and.returnValue(of(studentPayload));
    stubWebSocketService.getNotified.and.returnValue(of('success'));
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

In my component, it look like this

  constructor(
    private studentService: StudentsCrudService,
    private notificationService: NotificationService,
    private webSocketNotifier: WebsocketService
  ) {}

  ngOnInit(): void {
    this.studentSubscription();
    this.webSocketSubscription();
  }

  studentSubscription() {
    this.studentQueryRef =  this.studentService
    .getAllStudents()
    this.initSubscription.add(
      this.studentQueryRef
        .valueChanges.subscribe((response) => {
          this.paginatedStudents = {...response.data.paginateStudents}
        })
    );
  }

When I run the test im getting Cannot read properties of undefined (reading 'subscribe') at StudentsListComponent.studentSubscription. I tried so many things but nothing worked.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

゛时过境迁 2025-01-20 05:53:27

第一个 fixture.detectChanges 是在调用 ngOnInit 时发生的。

您已正确模拟 studentService,但没有错误地模拟 getAllStudents 的返回。

试试这个(下面的评论是!!):

const stubStudentService = jasmine.createSpyObj('StudentsCrudService',['getAllStudents','updateStudent']);
const stubWebSocketService = jasmine.createSpyObj('WebsocketService',['getNotified']);

describe('StudentsListComponent', () => {
  let component: StudentsListComponent;
  let fixture: ComponentFixture<StudentsListComponent>;
  // !! make the following changes
  let stubStudentService: jasmine.SpyObj<StudentCrudService>;
  let stubWebSocketService: jasmine.SpyObj<WebsocketService>;
  
  beforeEach(async () => {
    // !! assign the spies in a beforeEach so they are fresh for every test
    stubStudentService = jasmine.createSpyObj('StudentsCrudService', 
      ['getAllStudents','updateStudent']);
    stubWebSocketService = jasmine.createSpyObj('WebsocketService', 
    ['getNotified']);

    await TestBed.configureTestingModule({
      declarations: [StudentsListComponent],
      imports: [],
      providers: [
        { provide: StudentsCrudService, useValue: stubStudentService },
        { provide: WebsocketService, useValue: stubWebSocketService },
        NotificationService,
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(StudentsListComponent);
    // !! change below to return object of valueChanges
    stubStudentService.getAllStudents.and.returnValue({ valueChanges: of(studentPayload) });
    stubWebSocketService.getNotified.and.returnValue(of('success'));
    component = fixture.componentInstance;
    // !! the below fixture.detectChanges will call ngOnInit
    fixture.detectChanges();
  });

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

上面的内容有望解决您的问题。

The first fixture.detectChanges is when ngOnInit is called.

You have mocked studentService correctly but you haven't mocked the return of getAllStudents incorrectly.

Try this (follow comments with !!):

const stubStudentService = jasmine.createSpyObj('StudentsCrudService',['getAllStudents','updateStudent']);
const stubWebSocketService = jasmine.createSpyObj('WebsocketService',['getNotified']);

describe('StudentsListComponent', () => {
  let component: StudentsListComponent;
  let fixture: ComponentFixture<StudentsListComponent>;
  // !! make the following changes
  let stubStudentService: jasmine.SpyObj<StudentCrudService>;
  let stubWebSocketService: jasmine.SpyObj<WebsocketService>;
  
  beforeEach(async () => {
    // !! assign the spies in a beforeEach so they are fresh for every test
    stubStudentService = jasmine.createSpyObj('StudentsCrudService', 
      ['getAllStudents','updateStudent']);
    stubWebSocketService = jasmine.createSpyObj('WebsocketService', 
    ['getNotified']);

    await TestBed.configureTestingModule({
      declarations: [StudentsListComponent],
      imports: [],
      providers: [
        { provide: StudentsCrudService, useValue: stubStudentService },
        { provide: WebsocketService, useValue: stubWebSocketService },
        NotificationService,
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(StudentsListComponent);
    // !! change below to return object of valueChanges
    stubStudentService.getAllStudents.and.returnValue({ valueChanges: of(studentPayload) });
    stubWebSocketService.getNotified.and.returnValue(of('success'));
    component = fixture.componentInstance;
    // !! the below fixture.detectChanges will call ngOnInit
    fixture.detectChanges();
  });

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

The above should hopefully fix your problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文