【问题标题】:Testing a component which calls an async function测试调用异步函数的组件
【发布时间】:2019-01-13 09:26:27
【问题描述】:

我有一个react 组件,它调用作为prop 传入的async 函数,然后调用then 函数中的另一个函数。

我在下面简单化了它作为插图。

例如

const Form = ({ doSomething, closeModal }) => 
<form onSubmit={(e) => {doSomething().then(() => closeModal())
}}>
...
</form>

我正在尝试测试 closeModal 是这样调用的:

it('should doSomething then call closeModal', () => {

  const doSomethingStub = sinon.stub().resolves()
  const closeModalStub = sinon.stub()

  const props = {
    doSomething: doSomethingStub,
    closeModal: closeModalStub
  }

  const wrapper = shallow(<Form {...props}/>)

  wrapper.find(`form`).simulate(`submit`)

  expect(doSomethingStub.called).toEqual(true)
  expect(closeModalStub.called).toEqual(true)

})

在我的示例中,只有第一个期望是正确的。我对 sinon.stub 设置做错了吗?或者我期待什么?感觉像是小事,但我无法确定

【问题讨论】:

    标签: javascript reactjs unit-testing sinon stub


    【解决方案1】:

    你说得对,只是需要稍作改动:

    then 将回调排队等待执行。回调在当前同步代码完成并且事件循环抓取接下来排队的任何内容时执行。

    thenonSubmit() 中排队的回调有机会运行之前,测试正在运行完成并失败。

    给事件循环一个循环的机会,以便回调有机会执行,这应该可以解决问题。这可以通过使您的测试函数异步并等待您想要暂停测试并让任何排队的回调执行的已解决承诺来完成:

    it('should doSomething then call closeModal', async () => {
    
      const doSomethingStub = sinon.stub().resolves()
      const closeModalStub = sinon.stub()
    
      const props = {
        doSomething: doSomethingStub,
        closeModal: closeModalStub
      }
    
      const wrapper = shallow(<Form {...props}/>)
    
      wrapper.find(`form`).simulate(`submit`);
    
      // Pause the synchronous test here and let any queued callbacks execute
      await Promise.resolve();
    
      expect(doSomethingStub.called).toEqual(true)
      expect(closeModalStub.called).toEqual(true)
    
    });
    

    【讨论】:

    • 完美,谢谢,我知道我会错过一些愚蠢的东西,我的断开连接是我认为stub.resolves() 会返回一个可以解决的承诺,但我不知道在测试中如何await 那个具体的承诺。
    猜你喜欢
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多