且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular 2 - Mocking - 没有HTTP提供商

更新时间:2022-06-18 22:00:10

问题是这个

@Component({
  providers: [ APICaller ] <========
})
export class EventsPage {

通过这样,组件将尝试创建自己的 APICaller 。这将覆盖您在 TestBed (即模拟)中所做的任何配置。

By having that, the component will try to create its own instance of the APICaller. This overrides any configurations you make in the TestBed (i.e. the mock).

您可以做的是覆盖创建它之前的组件

What you can do is override the component before you create it

beforeEach(() => {
  TestBed.configureTestingModule({})

  TestBed.overrideComponent(EventsPage, {
    set: {
      providers: [
        { provide: APICaller, useValue: mockApiCaller }
      ]
    }
  })
})

另见:

  • Override Component Providers