4

我正在尝试为ActivatedRoute. 这是我的测试的样子。

it("should check if subscribes are called in init", () => {
    const subRouteSpy = spyOn(activatedRouteStub.paramMap, "subscribe");
    component.ngOnInit();
    expect(subRouteSpy).toHaveBeenCalled();
});

我的TestBed config

const activatedRouteStub = {
  paramMap: {
    subscribe() {
      return of();
    }
  }
};

TestBed.configureTestingModule({
  declarations: [HomeFilterDrawerComponent],
  providers: [
    { provide: ActivatedRoute, useValue: activatedRouteStub }
  ],
  imports: [
    FormsModule,
    StoreModule.forRoot(appReducers),
    HttpClientTestingModule,
    RouterTestingModule
  ]
}).compileComponents();

测试一直失败,让我Expected spy subscribe to have been called.不确定我在这里到底做错了什么。

组件内部ngOnInit的代码。

this.route.paramMap.subscribe(params => {
  if (params["params"].slug !== undefined) {
  }
});
4

1 回答 1

6

activatedRouteStub您通过useValue. 因此,您正在监视原始存根对象,但您的组件会看到一个没有附加间谍的克隆对象。

在指南中提到

始终从注入器获取服务 不要引用在测试主体中提供给测试模块的 userServiceStub 对象。这没用!注入到组件中的 userService 实例是一个完全不同的对象,是提供的 userServiceStub 的克隆。

要解决此问题,您需要使用以下方法获取对克隆对象的引用TestBed.get

let activatedRoute;

const activatedRouteStub = {
  paramMap: {
    subscribe() {
      return of();
    }
  }
};

TestBed.configureTestingModule({
  declarations: [HomeFilterDrawerComponent],
  providers: [
    { provide: ActivatedRoute, useValue: activatedRouteStub }
  ],
  imports: [
    FormsModule,
    StoreModule.forRoot(appReducers),
    HttpClientTestingModule,
    RouterTestingModule
  ]
}).compileComponents();

beforeEach(() => {
  fixture = TestBed.createComponent(NewsComponent);
  component = fixture.componentInstance;

  // Get a reference to the injected value
  activatedRoute = TestBed.get(ActivatedRoute);
});

it("should check if subscribes are called in init", () => {
  // Spy on the injected value
  const subRouteSpy = spyOn(activatedRoute.paramMap, "subscribe");
  component.ngOnInit();
  expect(subRouteSpy).toHaveBeenCalled();
});

或者,您可以保持代码不变,但更改useValueuseFactory. 这将允许您绕过克隆行为:

providers: [{ provide: ActivatedRoute, useFactory: () => activatedRouteStub }]
于 2019-08-14T16:39:50.953 回答