Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Jest testing #5718

zZHorizonZz started this conversation in Ideas
Discussion options

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).

You must be logged in to vote

Replies: 1 comment

Comment options

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.

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Ideas
Labels
None yet
Converted from issue

This discussion was converted from issue #5716 on September 17, 2024 17:15.

AltStyle によって変換されたページ (->オリジナル) /