Skip to content
Advertisement

Using Spies and Mocks on complex objects with Jest

I’m fairly new to testing and writing tests for a currently uncovered javaScript codebase using Jest. The code covers some niche use cases, as its conditionally injected and executed by the browser during page load. Anyway, I’m having issues mocking up custom objects. Here’s the function in question:

JavaScript

As far as I understand, I need to mock both window.location.pathname to return a string, and I need to mock window.TOOL.cookie.setCookie() as a mock function. Here’s my attempt at the test:

JavaScript

The test fails, saying that window.TOOL.cookie.setCookie was called 0 times. I’ve dug into the process, and found that window.location.pathname is executing as expected, and thus the code is entering the conditional that calls window.TOOL.cookie.setCookie. I think the problem is somewhere in how I’m mocking window.TOOL.cookie.setCookie, but I haven’t been able to find any help that describes how to mock methods so many .’s deep.

Thanks in advance for the help!

Advertisement

Answer

Just use Object.defineProperty() defines property directly on window object.

E.g.

index.js:

JavaScript

index.test.js:

JavaScript

unit test result:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement