13

我正在尝试使用 jasmine 为 getCurrentNavigation().extras.state 编写单元测试。

为了解决这个问题,我试图窥探这个路由器方法。

我的组件文件,

@Component({
  selector: 'app-location-list',
  templateUrl: './location-list.component.html',
  styleUrls: ['./location-list.component.scss']
})
export class LocationListComponent implements OnInit{

  locationId;
  locationName;
  constructor(private activatedRoute: ActivatedRoute, private router: Router) {
    if (this.router.getCurrentNavigation().extras.state) {
      this.locationId = this.router.getCurrentNavigation().extras.state.locationId;
    }
    if (this.router.getCurrentNavigation().extras.state) {
      this.locationName = this.router.getCurrentNavigation().extras.state.locationName;
    }
  }
  ngOnInit() { }
}

我的规格文件,

describe('LocationListComponent ', () => {
  let component: LocationListComponent ;
  let fixture: ComponentFixture<LocationListComponent >;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        LocationListComponent 
      ],
      providers: []
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LocationListComponent );
    component = fixture.componentInstance;
    spyOn(Router.prototype, 'getCurrentNavigation').and.returnValues({ 'extras': { 'state': { 'locationId': 100, 'locationName': "UK" } } });
    fixture.detectChanges();
  });

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

但我收到以下错误,

TypeError: Cannot read property 'extras' of null

谁能帮我解决这个问题。我在用着Angular 7.2

4

4 回答 4

15

您可以使用stub&轻松完成此操作,如果您可以在单独的文件中创建它,也可以在其他文件useClass中重用它,然后尝试:specexport class RouterStub

spec文件中创建一个stub将具有与以下相同的方法Router

class RouterStub{
 getCurrentNavigation(){
   return {
      extras: {
         state:{
           locationId: 'someId',
           locationName: 'someName'
         }
       }
     }
   }
}

并在beforeEach()块中:

describe('LocationListComponent ', () => {
  let component: LocationListComponent ;
  let fixture: ComponentFixture<LocationListComponent >;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        LocationListComponent 
      ],
      providers: [ {provide: Router, useClass: RouterStub}]
    })
      .compileComponents();
  }));

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
于 2019-08-24T16:46:11.030 回答
12

如果我们尝试同时使用两者RouterTestingModule{provide: Router, useClass: RouterStub}它会抛出错误cannot read property 'root' of undefined

所以我们可以直接为 Route 创建 spy 并返回它的值

describe('LocationListComponent', () => {
  let component: LocationListComponent ;
  let fixture: ComponentFixture<LocationListComponent>;
  let router: jasmine.SpyObj<Router>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        LocationListComponent 
      ],
    })
      .compileComponents();
  }));

  beforeEach(() => {
    router = TestBed.get(Router);
    spyOn(router, 'getCurrentNavigation').and.returnValue({ extras: { state: { message: 'msg'} } } as any);
    fixture = TestBed.createComponent(LocationListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
于 2020-04-23T08:45:36.777 回答
0

单元测试router.getCurrentNavigation()可以通过 3 个简单的步骤完成:

  1. 创建模拟路由器对象:

    const mockRouter = {
      getCurrentNavigation: jasmine.createSpy('getCurrentNavigation')
    };
    
  2. 将其注入providers数组:

    providers: [{ provide: Router, useValue: mockRouter }]
    
  3. beforeEach()在函数中返回所需的模拟值

    mockRouter.getCurrentNavigation.and.returnValue({
      extras: {
        state: {
          test: ''
        }
      }
    });
    
于 2021-11-02T10:40:32.980 回答
-2

您需要从夹具获取路由器实例

router = fixture.debugElement.injector.get(Router);
于 2019-08-23T09:59:08.577 回答