【问题标题】:Angular unit test, mock property of providerAngular 单元测试,提供者的模拟属性
【发布时间】:2018-10-15 14:53:05
【问题描述】:

我对单元测试非常陌生,尤其是 Angular。我有一个问题,在我的TestBed.configureTestingModule 中,我有一个具有私有 getter 的提供程序,而这个 getter 依赖于一个自定义的通用服务,该服务从文件中获取值。如何在不必依赖搜索特定文件的自定义服务的情况下模拟此值?假设吸气剂是url。我试过了

{
   provide: SomeService, useValue: {
     url: 'www.test.com'
   }
},

然后我的组件this.someService.SomeFunction is not a function 出现错误,我错过了什么?

【问题讨论】:

  • 创建一个具有相同结构但可以是部分的模拟类,使用它的一个实例作为useValue。 provide: SomeService, useValue: mockSomeService

标签: angular karma-jasmine


【解决方案1】:

假设提供者指的是服务,一个优雅的方法是使用 jasmine 工具 spyOnProperty

类似这样的事情,你有一个私人吸气剂

    @Injectable()
    export class TestService {
    
      private _url: string = 'www.random.com';
    
      constructor() { }
    
      private get url(): string {
        return this._url;
      }
    }

并像这样测试它

    describe('TestService', () => {
    
      let testService: TestService;
    
      beforeEach(() => {
    
        TestBed.configureTestingModule({
            imports: [ ],
            providers: [ TestService ]
        });
    
        testService = TestBed.get(TestService);
        
      });

      it('tests getter with property Spy', () => {
        expect(testService.url).toEqual('www.random.com');

        const urlSpy = spyOnProperty(testService, 'url', 'get').and.returnValue('www.happy.com');

        expect(testService.url).toEqual('www.happy.com');

      });
    });

【讨论】:

  • 这是 jasmine 的旧版本,现在它的 API 中缺少它。换什么
  • @IamStalker 它没有丢失,根据docs,spyOnProperty 仍在 3.5 中使用。
猜你喜欢
  • 1970-01-01
  • 2015-03-04
  • 2015-04-03
  • 2016-12-15
  • 2013-09-20
  • 2019-08-11
  • 1970-01-01
  • 2010-09-10
  • 2020-05-01
相关资源
最近更新 更多