Jasmine 2.0 async done() and angular-mocks inject() in same test it()

JavascriptAngularjsUnit TestingMockingJasmine

Javascript Problem Overview


My usual test case looks like

it("should send get request", inject(function(someServices) {
     //some test
}));

And Jasmine 2.0 async test should look like

it("should send get request", function(done) {
     someAsync.then(function(){
         done();
     });
});

How can I use both done and inject in one test?

Javascript Solutions


Solution 1 - Javascript

This should work; I ran into the same problem when I updated to Jasmine 2.0

it("should send get request", function(done) {
    inject(function(someServices) {
        //some async test
        done();
    })(); // function returned by 'inject' has to be invoked
});

Solution 2 - Javascript

An IMPORTANT note is the brackets after the inject call. Eg.

inject(function(someServices) {
   //some async test
   done();
})();  <-- these brackets here important.

If you look at the type of inject:

export declare function inject(tokens: any[], fn: Function): () => any;

You can see it returns a function, so you were getting no output because you forgot to call the function!!

If you think about it, it makes sense that it returns a function, because it takes a function!

So the extra parentheses should solve all problem!

Working Example:

  it('should allow you to observe for changes', function(done) {
    inject([GlobalStateService], (globalStateService: GlobalStateService) => {
      globalStateService.observe("user", storageType.InMemoryStorage, (user: string) => {
        expect(user).toBe("bla");
        done();
      });

      globalStateService.write({ user: "bla"}, storageType.InMemoryStorage);
    })();
  });

Solution 3 - Javascript

To add to the answer of @Scott Boring and to the comment of @WhiteAngel who mentionned that the code inside inject was never called.

This worked for me:

it("should send get request", function(done) {
    inject(function(someServices) {
       //some async test
       done();
    })();
});

Solution 4 - Javascript

You could write the test like that:

describe("Some service'", function () {    
	var service;
    var data;

    beforeEach(function (done) {   

        module('app');

        inject(function (someService) {
            service = someService;
        });
		
		service
			.getData()
			.then(function(result) {
				data = result;
				done();
			});
    });	

    it('should return a result', function () {	
        expect(data).toBeDefined();
    });	
}

Solution 5 - Javascript

For Angular 5.2.0: @scott-boring's approach did not work for me. What did work is using the TestBed.get() to get the services instead of inject(), as described in the docs:

describe('TooltipComponent', () => {
  let component: TooltipComponent;
  let fixture: ComponentFixture<TooltipComponent>;
  let myService: MyService;

  beforeEach(async(() => {
    const myServiceSpy = jasmine.createSpyObj('MyService', ['calc']);

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

    myService = TestBed.get(MyService);
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should render correctly', (done) => {
    component.render();

    setTimeout(() => {
      expect(myService.calc).toHaveBeenCalled();
      done();
    }, 1000);
  });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhuston007View Question on Stackoverflow
Solution 1 - JavascriptScott BoringView Answer on Stackoverflow
Solution 2 - JavascriptArie MilnerView Answer on Stackoverflow
Solution 3 - JavascriptPierre-Luc GregoireView Answer on Stackoverflow
Solution 4 - JavascriptDavid BohunekView Answer on Stackoverflow
Solution 5 - JavascriptFlorian GösseleView Answer on Stackoverflow