0

I have a function like:

  public openCamera = (obj) => {
    this._nativeCamera.getPicture()
      .subscribe((selectedImage) => {
        obj.avatar = selectedImage;
      });
  };

Now I want to test this function.

it('should pass', function(){
  let e = new EventEmitter();
  let obj = {};
  spyOn(mockNativeCamera,'getPicture').and.callFake(()=>e);
  sut.openCamera(obj);
  e.emit('Hello Dolly');
  expect(obj.avatar).toBe('Hello Dolly'); // This should be checked after subscription has finished, but happens synchronously and thus fails
});

Problem is that although this test should be async, I do not know how to hook to the execution of the asynchronous execution. I thought of subscribing to the event emitter inside the test, but there is no guarantee which subscription callback will be called first, so this sounds like a bad idea.

Any thoughts?

masimplo
  • 3,674
  • 2
  • 30
  • 47
  • maybe not the problem I'm not sure, but assign new value to `avatar` which is a argument of `openCamera` does not change its reference or value out of `openCamera` function. – Jiang YD May 20 '16 at 10:10
  • No, that is not the problem, and I just changed the above code to remove any ambiguity of such issues. – masimplo May 20 '16 at 13:08
  • I'm not sure exactly what your environment is, but I don't see any asynchronous code in your test. subscribe() and emit() should both synchronous. Calling e.subscribe(function(x) { foo.value = x }); e.emit(x); should work fine in a jasmine test. – Johnny C May 22 '16 at 16:40

0 Answers0