ค้นหาเว็บไซต์

การทดสอบหน่วย - Jasmine route spy - undefined ไม่ใช่วัตถุ (กำลังประเมิน 'navigate.calls.mostRecent().args')


ฉันกำลังพยายามทดสอบหน่วยของคอมโพเนนต์ Angular2 ที่ใช้การกำหนดเส้นทาง ฉันมี:

class MockRouter {
}

class MockAuth {
  isLoggedIn(){
    return false;
  }
}

describe('Home', () => {
  beforeEach(() => TestBed.configureTestingModule({
    providers: [
      BaseRequestOptions,
      { provide: Router, useClass: MockRouter },
      HomeComponent,
      { provide: AuthenticationService, useClass: MockAuth }
    ]
  }));

  it('should navigate to login', inject([HomeComponent], (home: HomeComponent) => {
    let navigate = jasmine.createSpy('navigate');
    expect(navigate.calls.mostRecent().args[0]).toEqual(['/login']);
  }));
});

แต่ฉันกำลังได้รับข้อผิดพลาด:

TypeError: undefined ไม่ใช่อ็อบเจ็กต์ (กำลังประเมิน 'navigate.calls.mostRecent().args') ใน config/spec-bundle.js (บรรทัด 41757)

ฉันคิดว่าการใช้ jasmine spy เป็นวิธีที่ถูกต้อง แต่ฉันพลาดบางอย่างไป - ฉันทำอะไรผิดหรือ?

คำตอบ #1

คุณควรเพิ่มสปายเข้าไปในคลาส MockRouter เพื่อให้สปายสอดแนมการเรียก navigate ใน Router

class MockRouter {
  navigate = jasmine.createSpy('navigate');
}

describe('Home', () => {
  let mockRouter;
  let fixture;
  let component: HomeComponent;

  beforeEach(() => {
     mockRouter = new MockRouter();
     TestBed.configureTestingModule({
        declarations: [ HomeComponent ]
        providers: [
          BaseRequestOptions,
          { provide: Router, useValue: mockRouter },
          { provide: AuthenticationService, useClass: MockAuth }
        ]
      });
      fixture = TestBed.createComponent(HomeComponent);
      component = fixture.createComponent;
  });

  it('should navigate to login', () => {
    // calls component.ngOnInit
    fixture.detectChanges();

    // assuming some navigation has been done
    expect(mockRouter.navigate).toHaveBeenCalledWith(['/login']);
  });
});

ประกาศ :

  • HomeComponent อยู่ใน declarations ไม่ใช่ใน providers
  • เราถือการอ้างอิงไปยังม็อกในทดสอบ และใช้ useValue แทน useClass เมื่อเรากำหนดค่า