Good Day,
I am quite new to Jasmine Framework and trying hard to understand a test suite for a function given below:
constructor() {
this.showToast = true;
}
simulateSendingMessage() {
return new Promise((resolve) => {
setTimeout(() => {
this.showToast = false;
resolve("Hello");
}, 4500);
});
}
Test Suite:
it('should wait half a second', (done) => {
const obj: Car = new Car();
const clock = jasmine.clock().install();
let messagePromise = obj.simulateSendingMessage();
clock.tick(4500);
messagePromise.then(() => {
expect(obj.showToast).toBe(false);
clock.uninstall();
done();
});
});
The above test case executes successfully.
Step 1: Create an instance of Class.
const obj: Car = new Car();
Step 2: Install the clock.
const clock = jasmine.clock().install();
Step 3: Assign the promise to the variable.
let messagePromise = obj.simulateSendingMessage();
Step 4: And then moving the time ahead using .tick
clock.tick(4500);
Step 5: Wait for the promise to resolve uninstall the clock and test the expectations.
Here I have a set of question's, which confuse me from a StackOverflow link which says
The install() function actually replaces setTimeout with a mock function that jasmine gives us more control over.
- Does this mean that what ever time I pass in the tick will overwrite the actual time passed in "setTimeout"?
But this does not actually happen. Then why the author says below?(Because we have to actually wait for the time given in "setTimeout")
because no actual waiting is done. Instead, you manually move it forward with the tick() function, which is also synchronous.
- Author also provided an example
Suppose you had a function that internally set a timeout of 5 hours. Jasmine just replaces that setTimeout call so that the callback will be called when you call tick() so that the internal counter reaches or exceeds the 5 hour mark. It's quite simple!
If in the function we have a setTimeout to execute in 5hr's then does the test case have to wait for 5hr's? If I am getting this wrong what would be the test suite for it?
Please help me get over these hurdles. Any suggestion would be appreciated.
Also, I have created a GitHub repository where I wanted to test the exact function but with .tick(10) milliseconds but my test case execution of a single spec is taking a time of around 4999 ms to complete(Don't know why)
https://github.com/dollysingh3192/ts-babel-template/tree/testPromise
Thank you in advance.