Ishaan Taylor
Ishaan Taylor

Reputation: 1927

How can I fail a mocha test if it takes shorter than a given time period?

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.

Upvotes: 0

Views: 602

Answers (1)

Mark
Mark

Reputation: 92461

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.

Upvotes: 2

Related Questions