Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create to use CreateSpyObj to create a spy of all methods in a class?

I'm writing unit tests for my Angular app and I'm learning about how to use spies.

Currently, every service that my component uses, I have to write something like this

let fakeMyService = jasmine.createSpyObj('fakeMyService', ['method1', 'method2']);
fakeMyService.method1.and.returnValue(Observable.of());
fakeMyService.method2.and.returnValue(Observable.of());

TestBed.configureTestingModule({
      declarations: [MyComponent],
      providers: [
        { provide: MyService, useValue: fakeMyService }
      ]
    }).compileComponents();

Although this works, it doesn't seem like the best way to set up my spies. For one, I have to type every single function in MyService that I want to put spies in. Secondly, it's not strongly typed. So if I ever change the name, I won't know immediately and also then, I'll have to update it in every place.

Is there some sort of way where I can just specify the class and it'll automatically just return me a fake class with spies for all the methods?

So something like this

  let fakeMyService = jasmine.createSpyObj<MyService>();
like image 824
Diskdrive Avatar asked Nov 07 '22 22:11

Diskdrive


1 Answers

Try using the new spyOnAllFunctions feature:

let fakeMyService = spyOnAllFunctions(MyService);

be aware that this is a new feature and it's available only in the latest 3.x version of Jasmine.

Also be aware that this feature is not yet present in the current typing (@types/jasmine). There is a feature request about it here.

like image 185
Francesco Borzi Avatar answered Nov 15 '22 10:11

Francesco Borzi