Skip to content

Documentation: Vitest - Test cases change in latest updateΒ #127

@jaysin586

Description

@jaysin586

Change Type

Addition

Proposed Changes

In the past you were able to run test cases on components that had this library in it using the beforeEach or beforeAll in vitest to ensure that there was a matchMedia on the object like below:

    beforeAll(() => {
        Object.defineProperty(window, 'matchMedia', {
            writable: true,
            value: vi.fn().mockImplementation((query) => ({
                matches: false,
                media: query,
                onchange: null,
                addEventListener: vi.fn(),
                removeEventListener: vi.fn(),
                dispatchEvent: vi.fn()
            }))
        })
    })

Now with the recent changes in the latest build this is no longer the case as the matchMedia now gets hooked in on initialization of the library instead of only when there was a read from the writable.

The solution now is to move it a level above into your vitest.setup.ts file with an implementation looking similar to the below:

const mockMatchMedia = vi.fn().mockImplementation((query) => ({
    matches: false,
    media: query,
    onchange: null,
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
    dispatchEvent: vi.fn(),
    // Add these properties to better match the MediaQueryList interface
    matchMedia: true,
    mediaQueryList: true,
    // Add a method to simulate media query changes
    simulateChange: (matches: boolean) => {
        mockMatchMedia.mock.results[0].value.matches = matches
        if (mockMatchMedia.mock.results[0].value.onchange) {
            mockMatchMedia.mock.results[0].value.onchange()
        }
    }
}))

Object.defineProperty(window, 'matchMedia', {
    writable: true,
    value: mockMatchMedia
})

I am not sure if you want to add this to the documentation, but thought I would leave it here just in case you do or if someone is running into issues with the latest changes πŸ₯°

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions