currentSpec in Jasmine 2 is undefined

纵饮孤独 提交于 2019-12-13 02:34:56

问题


I want to upgrade my test suite to the latest Jasmine version 2.3.4. I have some custom helper methods for testing AngularJS stuff inside my spy_helper.js like this:

(function() {
  this.stubPromise = function(service, functionName) {
    var $q = jasmine.getEnv().currentSpec.$injector.get("$q")
    var $rootScope = jasmine.getEnv().currentSpec.$injector.get("$rootScope")

    var deferred = $q.defer();
    var spy = spyOn(service, functionName).andReturn(deferred.promise);
    spy.andResolveWith = function(value) {
      deferred.resolve(value);
      $rootScope.$apply();
      return spy;
    };
    spy.andRejectWith = function(value) {
      deferred.reject(value);
      $rootScope.$apply();
      return spy;
    };
    return spy;
  };
}).call(this);

// inside a test you can do
stubPromise(someService, 'foobar').andResolveWith("test");

The helper stubs a promise and immediately resolves or rejects the promise. I have a bunch of such helpers.

The problem with Jasmine 2 is, that jasmine.getEnv().currentSpec is undefined. This is intended by the Jasmine 2 developers, as far as I know.

But how could I adapt my helpers for Jasmine 2? I could extend the arguments to get the $injector or even $q and $rootScope, but that would result in unhandy tests like stubPromise(someService, 'foobar', $injector).andResolveWith("test"); AND you would have to inject the $injector on top of every test.

So, is there a way to get angular's $injector inside my helpers?

Furthermore in some other helpers, I need to catch the after method of a spec, to check if expected spies on promises where called jasmine.getEnv().currentSpec.after(flush);

Any help is appreciated, because those helpers saved me a lot of time, and I'd be not very happy to rewrite all of them or throw them out. Maybe there is also a library out there, which does something similar (and I didn't know it).

来源:https://stackoverflow.com/questions/32198174/currentspec-in-jasmine-2-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!