Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you put an asynchronous callback in beforeEach when using inject?

In my unit tests, I want to inject certain modules, and I want the beforeEach hook to be asynchronous. Basically, I'm looking for something like this:

beforeEach(inject(function(_$rootScope_, _$compile_, done) {
  ...
}));

However, this doesn't work, because Karma complains that there is no provider called doneProvider. Basically, it's trying to look up a provider for anything inside inject.

Done typically gets inserted in the beforeEach hook like this:

beforeEach(function(done) {
  ...
});

But how can I inject what I need and still have the beforeEach be asynchronous?

I also tried placing an injector function inside the beforeEach:

beforeEach(function(done) {
  inject(function(_$rootScope_, _$compile_) {
    ...
    done();
  });
});

But the test times out when I do this. For some reason, it seems that done cannot be called inside the inject callback. When I place the call to done outside the inject function, the stuff I am injecting never gets set.

Any ideas?

like image 881
A. Duff Avatar asked Jul 19 '26 07:07

A. Duff


1 Answers

Solution is pretty simple;

  beforeEach(inject(function(_$injector_) {
      $injector = _$injector_;
    }));

  beforeEach(function (done) {
      setTimeout(function () {
        console.log('Got injector: '+$injector);
        done();
      }, 100);
  });

SetTimeout is example of async task. You can put there yours. So just do not do any async job inside on inject and it will be fine.

Then you use $injector.get('$modal') or whatever you need.

like image 175
Michał Hernas Avatar answered Jul 22 '26 00:07

Michał Hernas