Jest: Timer and Promise don't work well. (setTimeout and async function)

前端 未结 3 1756
甜味超标
甜味超标 2020-11-28 06:57

Any ideas on this code

jest.useFakeTimers() 

it(\'simpleTimer\', async () => {
  async function simpleTimer(callback) {
    await callback()    // LINE-A         


        
3条回答
  •  心在旅途
    2020-11-28 07:18

    There is a use case I just couldn't find a solution:

    function action(){
      return new Promise(function(resolve, reject){
        let poll
        (function run(){
          callAPI().then(function(resp){
            if (resp.completed) {
              resolve(response)
              return
            }
            poll = setTimeout(run, 100)
          })
        })()
      })
    }
    

    And the test looks like:

    jest.useFakeTimers()
    const promise = action()
    // jest.advanceTimersByTime(1000) // this won't work because the timer is not created
    await expect(promise).resolves.toEqual(({completed:true})
    // jest.advanceTimersByTime(1000) // this won't work either because the promise will never resolve
    

    Basically the action won't resolve unless the timer advances. Feels like a circular dependency here: promise need timer to advance to resolve, fake timer need promise to resolve to advance.

提交回复
热议问题