Sinonjs - Advance Clock To 59 Minutes And Wait For 1 Minute Actually
I've a web component for auto-logout functionality which shows modal window with a message on 59th minute and stay for another minute in case of no activity. And logs out the user
Solution 1:
Sinon's fake timers are pretty easy to work with and are my favourite feature of sinon.
The usage goes like this
In your code
// in your codeeatCake() {
setTimeout(function() {
// eat cake after 10s
}, 10000); // 10000 === 10s
}
In your test
clock = sinon.useFakeTimers();
clock.tick(9000);
// check if cake is eaten - answer will be false
clock.tick(1000); // 9000 + 1000 === 10s// check if cake is eaten - answer will be true
So sinon basically fast forwards (programatically) the timer so our test can check for the desired result without actually waiting the time because all test frameworks usually have a wait timeout of 2s after which a test case will fail.
In your case, to wait for 59 minutes, you could write
clock.tick(1000 * 60 * 59); // 59 minutes// check if the modal has opened up
clock.tick(1000 * 60 * 1); // 1 minute// check if the user is logged out
And don't forget to restore the clock at the end as you've already done.
clock.restore();
Solution 2:
Your general problem is probably in the await
before your function (browser.execute
):
- advancing the clock before await is pointless (regarding anything like setTimeOut inside)... since any of those inner timing functions is not yet set up.
- advancing the clock after the
await <function>
is pointless because indeed, theawait
will wait...
The solution is to not use await with your (async) function but treat it like any other promise-returning function (which any async function actually is).
it('some test', async () => {
awaitnewPromise((resolve, reject) => {
// normally used with awaitfunctionToBeTested(...some params).then(
(value) => {
log('now it happend')
resolve()
},
(reason) => {
reject(reason)
}
)
// by not using await (despite deleteAction being an sync function)// but rather just chaining a then, this clock.tick gets run while// deleteAction is "running" resp. waiting for some timeout:
clock.tick(1000)
})
... some more asserts on the result...
(we can be rest-assured the command under test is completed here)
})
Post a Comment for "Sinonjs - Advance Clock To 59 Minutes And Wait For 1 Minute Actually"