Angular 测试、模拟仅构建其他服务的服务

Angular testing, mocking service that just constructs other services

我了解如何模拟对服务的函数调用。

虽然我有一个案例,我的 MainService 只是其他几个服务的包装器。

 export class MainService {
  constructor(
    public service1: Service1,
    public service2: Service2,
    public service3: Service3
){}

我的组件注入 MainService,例如调用 this.mainService.service2.getUsers()。

beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      providers: [
        FormBuilder,
        {
          provide: MainService,
          useValue: jasmine.createSpyObj('MainService', [
            'getUsers'
          ])
        }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    fixture = TestBed.createComponent(MyComponent)
  })

我创建了模拟 MainService 的 spyObject 并添加了 getUsers 函数,我认为这不起作用,因为 getUsers 函数不直接在 MainService 上。我该怎么做。

尝试:

const mockMainService = {
  service1: {
    // mock service 1 public methods and properties here,
  },
  service2: {
    getUsers: () => {....},
    // mock service 2 public methods and properties here,
  },
  service3: {
    // mock service 3 public methods and properties here.
  }
};
beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      providers: [
        FormBuilder,
        {
          provide: MainService,
          useValue: mockMainService,
        }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    fixture = TestBed.createComponent(MyComponent)
  })