测试一个正在订阅内部的函数

时间:2018-01-19 17:06:41

标签: javascript typescript testing jasmine rxjs

sub: Subject = new Subject();

function funToTest() {
  const localSubscription = this.sub.subscribe(() => {
    this.otherFunctionToBeCalled();
    localSubscription.unsubscribe();
  });
}

如何测试是否已调用otherFunctionToBeCalled()

it('should otherFunctionToBeCalled be called', () => {
  theComponent.funToTest();

  // doesn't work
  expect(theComponent.otherFunctionToBeCalled).toHaveBeenCalled();
  ----------------------------------------------------------------
  theComponent.sub.next('something');

  theComponent.funToTest();

  // doesn't work
  expect(theComponent.otherFunctionToBeCalled).toHaveBeenCalled();
  ----------------------------------------------------------------
  theComponent.funToTest();

  // doesn't work
  theComponent.sub.subscribe(() => {
    expect(theComponent.otherFunctionToBeCalled).toHaveBeenCalled();
  });
  ----------------------------------------------------------------
  spyOn(theComponent.sub, 'subscribe').and.callFake(() => {});

  theComponent.funToTest();
  // doesn't work
  expect(theComponent.otherFunctionToBeCalled).toHaveBeenCalled();
});

1 个答案:

答案 0 :(得分:0)

你似乎缺少的基本事情是

spyOn(theComponent, 'otherFunctionToBeCalled').and.callThrough();

我使用callThrough()而不是callFake(),当然您需要theComponent.sub.next('something')才能通过订阅投放内容。

<强>演示

const theComponent = {
  sub: new Rx.Subject(),
  otherFunctionToBeCalled: function() { return 'I need to be called' }
}

const funToTest = function () {
  const localSubscription = theComponent.sub.subscribe(() => {
    theComponent.otherFunctionToBeCalled();
    localSubscription.unsubscribe();
  });
}

describe('some tests', () => {
  it('should otherFunctionToBeCalled be called', () => {
    spyOn(theComponent, 'otherFunctionToBeCalled').and.callThrough();
    funToTest();
    theComponent.sub.next('something')
    expect(theComponent.otherFunctionToBeCalled).toHaveBeenCalled();
  })
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/jasmine-html.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.4/boot.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>