0

The scenario I am trying to test: I want to ensure a file is not cached, and as a result a process, which typically takes >10s, executes and completes.

I want to fail a mocha test if it takes any shorter than 10 seconds to complete. I've checked out the docs and other questions here on stackoverflow..how can I do this?

Thanks!

edit: This testing pattern may not be ideal - I was mostly just curious to what would come up for this specific question.

Ishaan Taylor
  • 1,817
  • 5
  • 17
  • 19
  • I don't think this is the right way to assert this test. Just because an operation typically takes a certain amount of time, doesn't mean that it always well under every condition. You should be asserting that the file is not cached AND test the other conditions. What is the file and how are you caching it? – kyle Oct 01 '18 at 22:27
  • It's an sqlite `.db` file I am storing to disk. I am checking to see if the file is cached, and as many other conditions as I can, as the functionality is opaque. I would also like to ensure the operation takes at least 10 seconds. Out of the 10s of times I've measured it, it's taken no less than 35 seconds. If the db file exists, the operation takes less than a second to complete. The timing is the last piece I want to verify for this operation, mostly to avoid silent failures down the line. – Ishaan Taylor Oct 02 '18 at 18:47

1 Answers1

2

You can take the time before the task and the time when it completes and assert that the difference is >=to what you want. Something like:

function doSomethingSlow(time){
    // wait time and resolve
    return new Promise(resolve => setTimeout(resolve, time))
}

// failed
let start = new Date
doSomethingSlow(2000).then(() => {
    let finish = new Date
    // assert(finish - start > 5000)
    console.log("did it take longer than 5 seconds: ", finish - start > 5000)
    })

Also, be aware that mocha imposes a time limit on tests. See here for changing it, but understand that the limit is there because long-running tests are normally frowned upon. You can often make the test just as effective and much quicker by stubbing out network/file access.

Mark
  • 90,562
  • 7
  • 108
  • 148