-
Notifications
You must be signed in to change notification settings - Fork 1k
Jest testing #5718
-
Description
I'm proposing to add potentially better support for testing with Jest, if possible, or add a section to the official documentation about testing. Currently, I was able to make Jest work with Material Web Components in Next.js, but there's a lot of configuration involved just to get it to function. In particular, there seem to be two methods used: matchMedia and attachInternals. I was able to find a workaround for matchMedia, which seems more likely to be a problem with Jest itself (https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom). However, there's also the attachInternals method, which requires creating a prototype. I found a solution that works, but as the author suggests, I don't think this is the correct way to implement it (https://stackoverflow.com/questions/77512630/what-is-the-correct-way-to-test-a-next-js-react-app-that-uses-the-latest-version).
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment
-
I had the same problem, but I also had to fix HTMLElement.animate()
which jsdom apparently doesn't support. I put the following in a file that I added to setupFilesAfterEnv
in my Jest config:
Object.defineProperty(window, "matchMedia", { writable: true, value: jest.fn().mockImplementation((query) => ({ matches: false, media: query, onchange: null, addListener: jest.fn(), // deprecated removeListener: jest.fn(), // deprecated addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(), })), }); global.HTMLElement.prototype.attachInternals = () => ({ setFormValue: () => {}, setValidity: () => {}, }); global.HTMLElement.prototype.animate = () => {};
Tests now pass without errors.
Beta Was this translation helpful? Give feedback.