Again, we’ll be continuing the series on Jest testing today – it’s been a while since I’ve written a post here, so sorry about that! Today I’m going to try to explain mocks, which could be interesting(!)
Mocks
When you test things, you often want to provide a “fake” version of some functionality, rather than the full version that may be provided within the browser (or sometimes Node) environment. Creating mock objects is actually quite simple. For example, if you wanted to mock the browser’s alert function, you would use the below:
import {jest} from '@jest/globals';
window.alert = jest.fn();
It really is that simple (for most use-cases) – if you wanted to then ensure this function was called, you would write your test like so:
// Import statements and describe block omitted for brevity
window.alert = jest.fn();
it('tests the alert function', () => {
alert();
// Note that `expect` below uses the function ref,
// and doesn't call the function itself
// (no brackets after alert)
expect(alert).toHaveBeenCalled();
}
You can also provide mock definitions for the functions, and check parameters that have been passed in, and other information. I suggest taking a look at the Jest documentation for more information
Callbacks
Another interesting use case I have found, is testing callbacks. Given the code below:
describe('callbacks', () => {
it('should pass', ()=>{
const callback = (a) => {
expect(a).toBe(1);
}
$('#test').on('click', (e)=> {
callback(1);
});
// We forgot to trigger `click`!!
});
});
The above code still passes, even though we didn’t remember to trigger the click action on our element! We get around this by using expect.assertions as below:
describe('callbacks', () => {
it('should pass', ()=>{
// The number parameter is how many times
// we believe `expect` should be called
expect.assertions(1)
const callback = (a) => {
expect(a).toBe(1);
}
$('#test').on('click', (e)=> {
callback(1);
});
})
})
Now if we run the test, it will fail, and we know we have missed something (in order to make the test pass, we would have to call $('#test').trigger('click'); at the bottom.
And that’s it for now – I will also be doing the final part in this series in the future, and, as always, feel free to contact me should you have any questions or comments.

