在具有异步功能的存根中未调用sinon spy [英] sinon spy is not called in a stub with async function

查看:69
本文介绍了在具有异步功能的存根中未调用sinon spy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 sinon 我要测试以下组件:

Using sinon and enzyme I wanna test the following component:

// Apple.js
class Apple extends Component {

  componentDidMount = () => {

    this.props.start();
    Api.get()
      .then(data => {
        console.log(data); // THIS IS ALWAYS CALLED
        this.props.end();
      });
  }

  render () {
    return (<div></div>);
  }
}

如果我只检查 endApy称为,这总是错误的。但是将其包装在 setTimeout 中将使其通过。为什么总是调用 console.log()但不调用 props.end ?为什么 setTimeout 可以解决此问题?有更好的方法吗?

If I just check endApy.called, it's always false. But wrapping it in a setTimeout will make it pass. Why console.log() is always called but not the props.end? Why setTimeout fixes it? Is there a better way of doing this?

// Apple.test.js
import sinon from 'sinon';
import { mount } from 'enzyme';
import Api from './Api';
import Apple from './Apple';


test('should call "end" if Api.get is successfull', t => {
  t.plan(2);
    sinon
        .stub(Api, 'get')
        .returns(Promise.resolve());

    const startSpy = sinon.spy();
    const endApy = sinon.spy();

    mount(<Apple start={ startSpy } end={ endApy } />);

    t.equal(startSpy.called, true);                    // ALWAYS PASSES 
    t.equal(endSpy.called, true);                      // ALWAYS FAILS
    setTimeout(() => t.equal(endApy.called, true));    // ALWAYS PASSES

    Api.get.restore();
});


推荐答案

Api.get 是异步函数,它返回一个Promise,因此要在测试中模拟异步调用,您需要调用 resolves 函数而不是 returns

Api.get is async function and it returns a promise, so to emulate async call in test you need to call resolves function not returns:


使存根返回一个Promise,该Promise会解析为所提供的值。构造Promise时,sinon使用Promise.resolve方法。您负责在不提供Promise的环境中提供polyfill。

Causes the stub to return a Promise which resolves to the provided value. When constructing the Promise, sinon uses the Promise.resolve method. You are responsible for providing a polyfill in environments which do not provide Promise.



sinon
  .stub(Api, 'get')
  .resolves('ok');

这篇关于在具有异步功能的存根中未调用sinon spy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆