Angular 单元测试,提供者的模拟属性

Exp*_*ngx 1 karma-jasmine angular

我对单元测试特别是 Angular 非常陌生。我有一个问题,在我的TestBed.configureTestingModule提供程序中,它具有私有 getter,并且该 getter 依赖于从文件中获取值的自定义通用服务。如何模拟此值,而不必依赖搜索特定文件的自定义服务?可以说吸气剂是url。我尝试过

{
   provide: SomeService, useValue: {
     url: 'www.test.com'
   }
},
Run Code Online (Sandbox Code Playgroud)

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

Luc*_*cho 5

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

像这样你有一个私人吸气剂

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

并像这样测试它

    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');

      });
    });
Run Code Online (Sandbox Code Playgroud)