首页 > 解决方案 > 带有 ActivatedRoute 的 Angular 测试组件

问题描述

我对使用 ActivatedRoute 的测试组件有一个大问题 - 我只想通过默认测试“component.toBeTruthy”

组件类:

@Component({
  selector: 'app-room',
  templateUrl: './room.component.html',
  styleUrls: ['./room.component.css']
})
export class RoomComponent implements OnInit {

  roomId:string;

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.roomId = this.route.snapshot.params.id;
  }

}

测试:

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

  beforeEach(async(() => {

    let temp = new ActivatedRouteStub();

    TestBed.configureTestingModule({
      declarations: [ RoomComponent ],
      imports: [MaterialModule, FormsModule, RouterModule, BrowserModule,BrowserAnimationsModule],
      providers: [MatDialog, MatToolbar, RoomService,
        {
          provide: ActivatedRoute, useValue: {}
        }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

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

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

问题是,当我开始测试时它失败并出现奇怪的错误:

Chrome 65.0.3325 (Mac OS X 10.13.4) ERROR { "message": "Uncaught NetworkError: 无法在 'XMLHttpRequest' 上执行 'send': 无法加载 'ng:///DynamicTestModule/RoomComponent_Host.ngfactory.js' .\nat http://localhost:9876/_karma_webpack_/polyfills.bundle.js:2206:25 \n\n错误:无法在“XMLHttpRequest”上执行“发送”:无法加载“ng:///DynamicTestModule/RoomComponent_Host” .ngfactory.js'.\n 在http://localhost:9876/_karma_webpack_/polyfills.bundle.js:4970:35 \n 在 XMLHttpRequest.proto.(匿名函数)[作为发送](http://localhost: 9876/_karma_webpack_/polyfills.bundle.js:3386:24)\n 在数组中。(node_modules/source-map-support/browser-source-map-support.js:107:134)\n 在 node_modules/source-map-support/browser-source-map-support.js:101:106\n

如果我this.roomId = this.route.snapshot.params.id;从 ngOnInit 中删除这一行,一切正常。

发生了什么?

标签: angularjasmineangular2-routingkarma-jasmine

解决方案


我的直觉说错误消息可能与实际问题无关。

问题是您正在{}用作ActivatedRoute. 然后,在您的组件中,您尝试访问ActivatedRoute在测试用例中是{}.

您可以尝试将您的替换providers为:

providers: [MatDialog, MatToolbar, RoomService,
{
  provide: ActivatedRoute, useValue: {
    snapshot: { params: { id: 123 } }
  }
}];

推荐阅读