javascript - React 中的额外等待会破坏异步测试

标签 javascript reactjs asynchronous jestjs enzyme

我有以下代码:

async fetchAndUpdate () {
  const endpoint = 'endpoint'
  this.setState({ configFetched: false })
  try {
    const response =
      await window.fetch(`https://${window.location.host}/${endpoint}`,
        { method: 'POST',
          credentials: 'same-origin'
        })

    if (!response.ok) {
      throw new Error(`statusText: ${response.statusText}, status: ${response.status}`)
    }

    // const result = await response.json()
    // if (!result) {
    //  throw new Error(`status: ${response.status}, result: false`)
    // }

    this.setState({ configFetched: true })
    console.log('End of implementation')
  } catch (exception) {
    console.error(`Failed to post data to ${endpoint} endpoint. Error: ${exception}`)
  }
}

我对此进行了测试:

it('should set configFetched when positive response is returned', async () => {
  const wrapper = shallow(<Component />)
  fetch.mockClear()
  fetch.mockReturnValueOnce(constructSuccessfulResponse(true))

  const fetchButton = wrapper.find(fetchButtonSelector)
  await fetchButton.simulate('click')

  console.log('Here comes the expect...')
  expect(wrapper.state().configFetched).toBeTruthy()
})

const constructSuccessfulResponse = (data) => {
  return Promise.resolve({
      ok: true,
      json: () => data
  })
}

它通过了预期的输出(第一个代码结束,比预期被检查)

End of implementation
Here comes the expect...

当我取消第一个代码片段中的 4 行注释时,问题就开始了。 测试开始失败,输出反转:

Here comes the expect...    
End of implementation

为什么这段特定的代码会改变一切?我该如何解决这个问题?

最佳答案

我通过将expect部分放在setTimeout中并在完成后调用done来绕过这个问题:

it('should set configFetched when positive response is returned', async (done) => {
  const wrapper = shallow(<Component />)
  fetch.mockClear()
  fetch.mockReturnValueOnce(constructSuccessfulResponse(true))

  const fetchButton = wrapper.find(fetchButtonSelector)
  await fetchButton.simulate('click')

  setTimeout(() => {
    expect(wrapper.state().configFetched).toBeTruthy()
    done()
  }, 1)
})

这有多邪恶?

关于javascript - React 中的额外等待会破坏异步测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53669081/

相关文章:

flash - 如何在 Actionscript 3 中对事件进行排序

ruby - 这个示例 tcp 套接字编程事件顺序安全吗?

javascript - 如何在 Bootstrap 插件中以货币格式显示输入字段中的数字?

javascript - 如何根据扩展修改数组

android - 使用 React Native 钩子(Hook)

javascript - 从用户信息返回一个值并将其显示在输入中

javascript - node-inspector 不调试 - 它立即停止执行

javascript - 使用 Node JS 16 在 DiscordJS 13 上创建嵌入消息 - Discord Bot

javascript - 重定向 react 路由器中的所有路由

opengl - 有没有办法判断OpenGL操作是否完成?