Expressingx
Expressingx

Reputation: 1572

Angular unit test, mock property of provider

I'm really new to unit testing and especially with Angular. I have a problem, in my TestBed.configureTestingModule I have provider which has private getter and this getter relies on an custom generic service which gets the value from a file. How can I mock this value without having to rely on the custom service which searches for a specific file? Lets say the getter is url. I've tried with

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

But then I get error in my component this.someService.SomeFunction is not a function, what am I missing?

Upvotes: 1

Views: 10999

Answers (1)

Lucho
Lucho

Reputation: 1547

Assuming with provider you mean a Service, an elegant way would be to use the jasmine tool spyOnProperty.

Something like this where you have a private getter

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

and test it like this

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

      });
    });

Upvotes: 5

Related Questions