Skip to content

Commit

Permalink
setTimeout_safe now accepts setTimeout impl fn (for mocking purposes)…
Browse files Browse the repository at this point in the history
…, working on the setTimeout_safe test
  • Loading branch information
xpl committed Dec 5, 2017
1 parent ab08593 commit 18ac2ed
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
8 changes: 6 additions & 2 deletions js/base/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,24 @@ const CryptoJS = require ('crypto-js')
//-----------------------------------------------------------------------------

const { RequestTimeout } = require ('./errors')
const log = require ('ololog')

//-----------------------------------------------------------------------------
// utility helpers

const setTimeout_safe = (done, ms, targetTime = Date.now () + ms) => { // setTimeout can fire earlier than specified, so we need to ensure it does not happen...
// setTimeout can fire earlier than specified, so we need to ensure it does not happen...
const setTimeout_safe = (done, ms, setTimeout = setTimeout /* for mocking purposes */, targetTime = Date.now () + ms) => {

let clearInnerTimeout = () => {}
let active = true

log (ms)

let id = setTimeout (() => {
active = true
const rest = targetTime - Date.now ()
if (rest > 0) {
clearInnerTimeout = setTimeout_safe (done, rest, targetTime) // try sleep more
clearInnerTimeout = setTimeout_safe (done, rest, setTimeout, targetTime) // try sleep more
} else {
done ()
}
Expand Down
9 changes: 3 additions & 6 deletions js/test/test_base.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,20 @@ describe ('ccxt base code', () => {

it.only ('setTimeout_safe is working', (done) => {

const setTimeout_impl = global.setTimeout

const start = Date.now ()
const calls = []

global.setTimeout = (done, ms) => { // simulates a defect setTimeout implementation that sleeps wrong time (100ms always in this test)
const brokenSetTimeout = (done, ms) => { // simulates a defect setTimeout implementation that sleeps wrong time (100ms always in this test)
calls.push ({ when: Date.now () - start, ms_asked: ms })
setTimeout_impl (done, 100)
return setTimeout (done, 100)
}

// ask to sleep 250ms
ccxt.setTimeout_safe (() => {
const end = Date.now () - start
log (calls)
global.setTimeout = setTimeout_impl
done ()
}, 250)
}, 250, brokenSetTimeout)
})

it ('calculateFee() works', () => {
Expand Down

0 comments on commit 18ac2ed

Please sign in to comment.