Search This Blog

Showing posts with label angular. Show all posts
Showing posts with label angular. Show all posts

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)

Jasmine runner TypeError 'next' in Angular5 Tests

I stumbled upon an error, which a karma runner gives me in some of our jasmine tests:

TypeError: Cannot read property 'next' of undefined
    at <Jasmine>
    at Function.continuer node_modules/q/q.js:1278:1)
    at UserContext.<anonymous> node_modules/q/q.js:1305:1)
    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)
    at <Jasmine>

I couldn't find something wrong with the test itself, but I noticed an strange import:

[async] from "q";

This was the reason for the strange error message. Correct import ist

[async] from "@angular/core/testing";