【问题标题】:Properly inject dependency in Angular2 tests在 Angular2 测试中正确注入依赖项
【发布时间】:2016-09-30 08:53:26
【问题描述】:

我正在努力测试一个注入了服务的 Angular2 组件。测试代码如下,但基本上是:

• SearchComponent 在构造函数中接受一个 FightService。

• 构造函数调用触发 HTTP 请求的 flightService.getFlights()。 flightService.getFlights() 返回一个 observable。

• 构造函数订阅填充 allSummaryItems 数组的 observable 返回。

我的 MockFlightService 没有被使用,它基本上失败了,说没有 Http 提供者(在 FlightService 构造函数中)。如果我将 HttpModule 添加到 TestBed 中的提供程序,那么它会关闭并触发真正的 Http 请求。

如何确保我使用的是 MockFlightService?即使在触发真正的 Http 请求时,这也会正确测试 observable,我可以看到订阅的方法没有被调用?

谢谢

class MockFlightsService {
  public getFlights = () => {
    return new Observable<any>(() => { return dummyData.json(); });
  };
}

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

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [SearchComponent],
      imports: [RouterModule],
      providers: [{ provide: FlightsService, useClass: MockFlightsService }]
    });

    fixture = TestBed.createComponent(SearchComponent);
    fixture.detectChanges();
  });

  it('should render list', fakeAsync(() => {
    fixture.whenStable();
    component = fixture.componentInstance;
    console.log(component.allSummaryItems); // this is empty, shouldn't be
  }));
});

我正在使用 Angular 2.0.1。

【问题讨论】:

    标签: angular jasmine karma-jasmine angular2-testing


    【解决方案1】:

    我的 MockFlightService 没有被使用,它基本上失败了,说没有 Http 提供者(在 FlightService 构造函数中)

    根据您显示的配置,我看到这种情况发生的唯一方法是,如果您在 @Component.providers 中列出了该服务。这将覆盖任何模块级提供程序。我整整一天都在扯头发,因为我完全忘记了我的头发。

    如果该服务应该是应用程序范围的提供者,则将其从@Component.providers 中取出并将其添加到@NgModule.providers

    如果您的目标是将服务限制在组件级别,那么您应该做的是覆盖测试组件中的提供程序,而不是将提供程序添加到测试模块中。

    TestBed.overrideComponent(SearchComponent, {
      set: {
        providers: [
          { provide: FlightsService, useClass: MockFlightsService }
        ]
      }
    });
    

    这应该在您创建组件之前完成。

    您可以在Overriding Test Providers 中查看更多信息。

    其他事情与错误无关。

    • 您对RouterModule 的使用。对于测试,您应该使用RouterTestingModule,如提到的here
    • whenStable 返回一个承诺。只是打电话,并不能保护你。你需要订阅它,然后在那里做你的事情。

      whenStable().then(() => {
        // Do stuff here. This is when the async tasks are completed.
      })
      
    • 查看this post,了解如何模拟Http(如果需要)的示例,这样您就不会在测试期间发出 XHR 请求。

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 2017-02-07
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多