【问题标题】:Angular testing component with ActivatedRoute带有 ActivatedRoute 的 Angular 测试组件
【发布时间】:2018-10-07 04:13:30
【问题描述】:

我在测试使用 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) 错误 { "message": "Uncaught NetworkError: 无法在 'XMLHttpRequest' 上执行 'send': 无法加载 'ng:///DynamicTestModule/RoomComponent_Host.ngfactory.js'。\nat http://localhost:9876/_karma_webpack_/polyfills.bundle.js:2206:25\n\nError: 无法执行在“XMLHttpRequest”上“发送”:无法加载“ng:///DynamicTestModule/RoomComponent_Host.ngfactory.js”。\n 在http://localhost:9876/_karma_webpack_/polyfills.bundle.js:4970:35\n 在 XMLHttpRequest.proto.(匿名函数)[作为发送](@987654323 @)\n 在 Array. (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

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

发生了什么事?

【问题讨论】:

  • 两件事:尝试在运行测试时关闭源映射,以获得更多关于失败的反馈;并考虑将RouterTestingModule 用于更可控的测试环境。
  • 我刚刚看到您使用路由器测试模块@jonrsharpe 的第一个答案,我完全没有注意到这一点。你应该用那个来回答!我正在删除我的其他 cmets 和答案,因为它们没用或只是鹦鹉学舌。
  • sourcemaps off 有帮助! - 我必须提供 {snapshot:{params:{id:''}}}

标签: angular jasmine angular2-routing karma-jasmine


【解决方案1】:

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

问题是您使用{} 作为ActivatedRoute 的提供者。然后,在您的组件中,您尝试访问ActivatedRoute,在测试用例中为{}

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

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

【讨论】:

    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 2017-11-19
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2017-02-27
    • 1970-01-01
    相关资源
    最近更新 更多