Jest is a JavaScript testing framework maintained by Facebook, Inc. It was designed and built by Christoph Nakazawa with a focus on simplicity and support for large web applications. Jest works seamlessly with projects using Babel, TypeScript, Node.js, React, Angular, Vue.js, and Svelte.
In this blog post, you will learn how to mock JavaScript events such as addEventListener
, onclick
, and DOMContentLoaded
using Jest. While the examples provided focus on these specific events, Jest allows you to mock any JavaScript event listener.
Let’s start with a simple example. Suppose you have the following JavaScript function:
module.exports = {
init: function () {
document.addEventListener("DOMContentLoaded", () => {
this.instance();
});
},
instance: function () {
console.log("Instance method called");
}
};
The init
function calls the instance
method when the DOMContentLoaded
event is triggered.
Now, let’s write a test case for the above function using Jest.
import eventModule from "./event";
test("It should pass", () => {
const instanceMock = jest.spyOn(eventModule, "instance");
document.addEventListener = jest
.fn()
.mockImplementationOnce((event, callback) => {
callback();
});
eventModule.init();
expect(document.addEventListener).toBeCalledWith(
"DOMContentLoaded",
expect.any(Function)
);
expect(instanceMock).toBeCalledTimes(1);
});
In this test case, we use Jest’s mocking capabilities. We mock document.addEventListener
using jest.fn()
and provide a custom implementation that triggers the callback immediately. By doing so, we simulate the DOMContentLoaded
event and ensure that the instance
method is called.
Mocking allows you to create controlled test environments where you can replace real objects with custom implementations. This helps isolate the code under test and focus on specific scenarios without worrying about the behavior of external dependencies. Jest provides a comprehensive mocking system, including mock functions and module mocking, to facilitate this process.
Happy Coding!
hello , actually i wanna test on eventsource.addeventlistener using jest+react testing lib. can u guide me for that
ReplyDeletesorry I see you comment very late. I will get back to you soon
Delete