During my test setup, I initialize a player
object in the beforeEach
block. Within my test logic, every time I call jest.advanceTimersByTime(2001)
, the player.seekable.mock.calls
count increases. As such, given that I make two calls to jest.advanceTimersByTime(2001)
, the total should be reflected as
player.seekable.mock.calls.length
equaling 2.
initPlayer.test.js
describe('testing', () => {
let player, seekableEnd;
beforeEach(() => {
seekableEnd = 120;
player = {
currentTime: jest.fn(),
seekable: jest.fn(() => {
return {
end: jest.fn().mockReturnValue(seekableEnd),
};
}),
}
});
it('should keep until the video has a seekable edge', async () => {
seekableEnd = undefined;
player.currentTime.mockReturnValue(10);
await initPlayer();
jest.advanceTimersByTime(2001);
seekableEnd = 100;
jest.advanceTimersByTime(2001);
expect(player.seekable.mock.calls.length).toBe(2);
});
});
I attempted to refactor my code by moving the player
object into a helper function, rather than defining it directly within the test. However, upon using this helper in my test file, the
player.seekable.mock.calls.length
value is now 1
instead of 2
as it was previously defined in the direct test setup. The reason for this discrepancy eludes me.
player.js
export function getPlayer(data) {
player = {
currentTime: jest.fn(),
seekable: jest.fn(() => {
return {
end: jest.fn().mockReturnValue(data.seekableEnd),
};
}),
}
}
export default getPlayer;
initPlayer.test.js
import { getPlayer } from './helpers/player';
describe('testing', () => {
let player, seekableEnd;
beforeEach(() => {
seekableEnd = 120;
const data = { seekableEnd };
player = getPlayer(data);
});
it('should keep until the video has a seekable edge', async () => {
seekableEnd = undefined;
player.currentTime.mockReturnValue(10);
await initPlayer();
jest.advanceTimersByTime(2001);
seekableEnd = 100;
jest.advanceTimersByTime(2001);
expect(player.seekable.mock.calls.length).toBe(2); <---- this is 1 now when using the extracted player helper
});
});