【问题标题】:Test a function which body is inside subscription测试主体在订阅内的函数
【发布时间】:2018-01-19 17:06:41
【问题描述】:
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();
});

【问题讨论】:

    标签: javascript typescript testing jasmine rxjs


    【解决方案1】:

    你似乎缺少的基本东西是

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-10
      • 2016-03-17
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 2019-01-30
      • 2015-08-05
      相关资源
      最近更新 更多