Search This Blog

Thursday, May 17, 2018

spyOn static Methods in jasmine tests

If you want to spy on a static method within your jasmine tests, you could do a simple spy like


beforeAll(async() =>{
  spyOn(UserService, "staticMethod").and.returnValue(true);
});


I'll tend to do this within beforeAll to avoid having problems when doing this in beforeEach. Within beforeEach you might end up in error messages like 

Error: <spyOn> : staticMethod has already been spied upon
    at <Jasmine>
    at UserContext.<anonymous> src/app/shared/components/result-detail/sample.component.spec.ts:74:5)
    at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
    at ProxyZoneSpec.webpackJsonp../node_modules/zone.js/dist/proxy.js.ProxyZoneSpec.onInvoke node_modules/zone.js/dist/proxy.js:128:1)
    at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:387:1)
    at Zone.webpackJsonp../node_modules/zone.js/dist/zone.js.Zone.run node_modules/zone.js/dist/zone.js:138:1)
    at runInTestZone node_modules/zone.js/dist/jasmine-patch.js:145:1)
    at UserContext.<anonymous> node_modules/zone.js/dist/jasmine-patch.js:160:1)

No comments:

Post a Comment