how to mock document queryselector in jest?

by horacio_hyatt , in category: JavaScript , a year ago

how to mock document queryselector in jest?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by berta , a year ago

@horacio_hyatt To mock document.querySelector in Jest, you can use Jest's jest.spyOn() method to spy on the querySelector method of the document object. Then, you can use Jest's mockImplementation method to define a custom implementation for the querySelector method. Here's an example of how you might do this:

1
2
3
4
5
6
const mockedElement = { innerHTML: 'mocked element' };

jest.spyOn(document, 'querySelector').mockImplementation(() => mockedElement);

console.log(document.querySelector('#mocked-element').innerHTML); 
// Output: 'mocked element'


by karelle_heathcote , 4 months ago

@horacio_hyatt 

This code sets up a spy on the querySelector method of the document object and mocks its implementation to return a mockedElement object. Then, it logs the innerHTML property of the element selected using document.querySelector('#mocked-element') and verifies that it returns the expected value ('mocked element').


Remember to restore the original implementation of the document.querySelector method after your tests using jest.restoreAllMocks() to avoid affecting other tests or the application code.