user1486133
user1486133

Reputation: 1457

Jest mock addEventListener "DOM Content loaded" for tests inside this check

I'm trying to write unit tests for logic that occurs inside a check for 'DOMContentLoaded'

Code example:

window.addEventListener('DOMContentLoaded', () => {
    // do stuff
    ...
});

In my tests I am already mocking the window object (as I have a util to set the window). So I was trying to mock addEventListener on my window mock:

jest.mock("./utils/window");
let mockWindow;
const mockWindowObject = {
  addEventListener: jest.fn().mockImplementation("DOMContentLoaded", () => true)
};


beforeEach(() => {
  jest.resetModules();
    
  mockWindow = require("./utils/window").default;
  mockWindow.mockReturnValue(mockWindowObject);
    
  require("./myComponent");
});

So before each I am correctly mocking the window, and then returning the object which contains the mock function addEventListener. I think I'm making a mistake in the mockImplementation part but I'm not sure what:

addEventListener: jest.fn().mockImplementation("DOMContentLoaded", () => true)

Upvotes: 0

Views: 1964

Answers (1)

João Pedro
João Pedro

Reputation: 46

I had the same problem using the jsdom library.

If you want to check changes made in DOMContentLoaded Event, just implement a eventListener in your test:

test('DOMContentLoaded changes', () => {
  document.addEventListener('DOMContentLoaded', () => {
    // your checks here
  });
})

In my case, I just need to use the testing library selectors to verify my changes in DOM.

You can check this here.

Upvotes: 3

Related Questions