2017-10-12 9 views
1

Jest의 비동기 테스트를 이해하려고합니다.Jest와 setTimeout을 사용하여 약속 테스트

내 모듈에는 부울을 허용하고 값의 약속을 반환하는 함수가 있습니다. executer 함수는 setTimeout을 호출하고 시간 제한 콜백에서 처음에 제공된 부울에 따라 약속이 해결되거나 거부됩니다. 코드는 다음과 같습니다.

const withPromises = (passes) => new Promise((resolve, reject) => { 
    const act =() => { 
    console.log(`in the timout callback, passed ${passes}`) 
     if(passes) resolve('something') 
     else reject(new Error('nothing')) 
    } 

    console.log('in the promise definition') 

    setTimeout(act, 50) 
}) 

export default { withPromises } 

Jest를 사용하여 테스트하고 싶습니다. 내 테스트 스크립트는이 같은 비트 보이는, 그래서 내가 농담이 제공하는 모의 타이머를 사용할 필요가 추측 :

import { withPromises } from './request_something' 

jest.useFakeTimers() 

describe('using a promise and mock timers',() => { 
    afterAll(() => { 
     jest.runAllTimers() 
    }) 


    test('gets a value, if conditions favor',() => { 
     expect.assertions(1) 
     return withPromises(true) 
      .then(resolved => { 
       expect(resolved).toBe('something') 
      }) 
    }) 
}) 

을 나는 다음과 같은 오류/실패 테스트, I 전화 여부를 jest.runAllTimers()

Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. 

내가 잘못하고있는 부분과 약속이 해결되는 테스트를 통과하기 위해해야 ​​할 일을 설명해 주시겠습니까?

답변

3

jest.useFakeTimers()에 대한 호출은 모든 타이머 기능을 모의합니다. 컨트롤이어야합니다. 자동으로 실행되는 타이머 대신 수동으로 타이머를 진행합니다. jest.runTimersToTime(msToRun) 함수는 msToRun 밀리 초 단위로 값을 전진시킵니다. 모든 타이머가 경과 할 때까지 빨리 감기를 원하고 모든 타이머가 완료되는 데 걸리는 시간을 계산하는 것이 번거롭기 때문에 Jest는 jest.runAllTimers()을 제공하므로 충분한 시간이 지난 것으로 가장합니다.

테스트의 문제는 당신이 시험에 jest.runAllTimers()를 호출하지 않을 것입니다,하지만 당신은 테스트가 완료 후 을 호출되는 afterAll 후크에서 호출. 테스트하는 동안 타이머는 0으로 유지되므로 콜백이 실제로 호출되지 않으며 미리 정의 된 간격 (기본값 : 5 초) 후에 Jest가 중단되어 잠재적으로 끝없는 테스트로 인해 멈추지 않도록합니다. 테스트가 끝난 후에 만 ​​jest.runAllTimers()으로 전화를 걸면 모든 테스트가 이미 끝났기 때문에 아무 것도하지 않습니다.

약속을 시작한 다음 타이머를 진행하면됩니다.

describe('using a promise and mock timers',() => { 
    test('gets a value, if conditions favor',() => { 
     expect.assertions(1) 
     // Keep a reference to the pending promise. 
     const pendingPromise = withPromises(true) 
      .then(resolved => { 
       expect(resolved).toBe('something') 
      }) 
     // Activate the timer (pretend the specified time has elapsed). 
     jest.runAllTimers() 
     // Return the promise, so Jest waits for its completion and fails the 
     // test when the promise is rejected. 
     return pendingPromise 
    }) 
}) 
+0

이 작품! 설명과 설명 및 코드 샘플을 보내 주셔서 감사합니다. –

관련 문제