【问题标题】:Jasmine: Is there a way to mock a locally used service?Jasmine:有没有办法模拟本地使用的服务?
【发布时间】:2020-11-03 10:26:38
【问题描述】:

我对 Angular 和 Jasmine 测试还很陌生,所以我试图检查这个方法是否正常工作,但我需要模拟 XmlReaderService,它只在本地使用,我怎么能模拟这个?我希望spyOn 有一些东西,但我无法理解它......

  private getElementSettings() {
    const xmlReader = new XmlReaderService(this.logger)
    xmlReader.requestXml(this.xmlServiceUrl + this.settingsFileName).then(() => {
      this.elementSettings = xmlReader.xmlJsoned['element_settings']
      this.getElementTypes()
      this.getElementList()
      this.getMonitors()
    }).catch((reason) => {
      this.logger.error('XML Request failed in getElementSettings()!')
      this.logger.info(reason, '[' + this.constructor.name + ']')
      this.delegate.errorCallback(650, 'XML Request failed - could not get smart home element definitions (ElementSettings.xml)', reason)
    })
  }

【问题讨论】:

  • 像你拥有它一样嘲笑它会很困难。如果在构造函数中注入服务,会更容易测试。在此处阅读具有依赖关系的组件:(angular.io/guide/testing-components-scenarios)。
  • 嗨@AliF50,谢谢!我最终对其进行了重构以提高可测试性...

标签: javascript angular testing mocking jasmine


【解决方案1】:

参见上面@AliF50 的评论。这种方式不太好测试...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    相关资源
    最近更新 更多