【问题标题】:Angular testing, mocking service that just constructs other servicesAngular 测试,模拟服务,只是构建其他服务
【发布时间】:2020-04-18 16:43:06
【问题描述】:

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

虽然我的 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 上。我该怎么做。

【问题讨论】:

  • jasmine.createSpyObj 应该模拟MainService 的公共方法。一旦你这样做了,如果正确地模拟,你不应该担心其他三个服务的依赖关系。
  • @AliF50 MainService 没有公共方法。不是直接将 service2 注入我的组件,而是注入 MainService,然后调用 this.mainService.service2.getUsers() 访问 service2

标签: javascript angularjs angular jasmine


【解决方案1】:

试试:

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)
  })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 2017-02-16
    • 2014-11-22
    • 2020-03-17
    相关资源
    最近更新 更多