【问题标题】:sinon spy.calledOnce inside a promise returns falsesinon spy.calledOnce 在 promise 中返回 false
【发布时间】:2017-07-24 01:11:29
【问题描述】:

我正在尝试测试是否调用了存根 promise 中的函数。不幸的是,该函数的间谍似乎仅在测试后才被调用。这是我的 React 代码的简化版本。

export default class TheComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  onSend(data) {
    AUtility.aPromise(data).then(() => {
      this.props.onSend(data);
      console.log("Props onSend was called!")
    });
  }

  render() {
    return null;
  }
}

这是我尝试运行的测试。

it('should call the props function', (done) => {
    const onSendSpy = spy();
    const promiseStub = stub(AUtility, 'aPromise').resolves('mock string');
    wrapper = shallow(<TheComponent onSend={onSendSpy} />
    wrapper.instance().onSend();
    expect(promiseStub.calledOnce).to.be.true;  //this passes
    expect(onSendSpy.calledOnce) //this fails
    done();
});

每当我运行测试时,第一个断言通过,但第二个断言不通过。但是,我的代码中的 print 语句在测试期间仍会打印字符串。似乎 done() 函数将在 promise 返回后完成测试,而不是在 then 块完全执行后完成。我怎样才能让这个测试通过?

【问题讨论】:

    标签: javascript mocha.js sinon stub spy


    【解决方案1】:

    我绝不是专家,但您可以尝试将两个期望语句包装在一个 setTimeout 函数中吗?

    setTimeout(() => { expect(promiseStub.calledOnce).to.be.true; expect(onSendSpy.calledOnce); done(); }, 0);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-24
      • 2019-06-16
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多