【问题标题】:Testing if method with Promise was called (Jest)测试是否调用了带有 Promise 的方法 (Jest)
【发布时间】:2018-05-31 19:05:28
【问题描述】:

我有一个初始化方法调用另一个返回承诺的方法,例如:

  initStuffAfterLoad() {
    const _this = this;
    const theInterval = window.setInterval(function() {
      if (thing) {
        window.clearInterval(theInterval);
        _this.getBanana()
          .then(response => {
            _this.getApple(response, _this);
          });
      }
    }, 100);
  }

并且我需要测试是否调用了 getBanana (jest/sinon)。到目前为止,我有:

  test('init function calls getBanana', () => {
    let thing = true
    const getBananaSpy = sinon.spy();
    sinon.stub(TheClass.prototype, 'getBanana').callsFake(getBananaSpy).resolves();

    jest.useFakeTimers();
    TheClass.prototype.initStuffAfterLoad();
    jest.runOnlylPendingTimers();

    expect(getBananaSpy.called).toBeTruthy();
    TheClass.prototype.getBanana.restore();
 });

但是它仍然在断言中收到false。我认为我没有正确处理 Promise 部分 - 最佳实践方法是什么?

【问题讨论】:

    标签: promise jestjs sinon


    【解决方案1】:

    我对 sinon 不熟悉,但这里有一种方法可以通过纯粹的玩笑来满足您的需求(更好的是,它还检查 getApple 是否在 getBanana 解析时被调用 :))

    jest.useFakeTimers()
    
    const _this = {
        getBanana: () => {},
        getApple: () => {}
    }
    
    const initStuffAfterLoad = () => {
        const theInterval = window.setInterval(function() {
            window.clearInterval(theInterval);
            _this.getBanana().then(response => {
                _this.getApple(response, _this)
            });
        }, 100);
    }
    
    test('', () => {
        let result
    
        _this.getBanana = jest.fn(() => {
            result = new Promise( resolve => { resolve() } )
            return result
        })
        _this.getApple = jest.fn()
    
        initStuffAfterLoad()    
    
        jest.runAllTimers()
                
        expect(_this.getBanana.mock.calls.length).toBe(1)
        return result.then(() => {
            expect(_this.getApple.mock.calls.length).toBe(1)
        })
    })
    

    代码测试:)


    通过测试\temp.test.js √ (25ms)

    测试套件:1 个通过,总共 1 个

    测试:1 次通过,总共 1 次

    快照:共 0 个

    时间:2.489s

    【讨论】:

    • 非常感谢!很高兴了解纯粹的玩笑实现
    猜你喜欢
    • 2019-07-24
    • 2021-09-06
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 2019-01-25
    • 2017-08-19
    • 2014-05-29
    • 1970-01-01
    相关资源
    最近更新 更多