score:0

you can automock the swr module so that mock functions like mockimplementationonce can be called on useswrconfig.

assuming you have the following react component.

import react from 'react'
import { useswrconfig } from 'swr'

export default function testcomponent() {
    const { mutate } = useswrconfig()

    return (
        <button onclick={() => { mutate('/api/user') }}>
            mutate
        </button>
    )
}

you would mock useswrconfig and its mutate function in your test as follows.

import react from 'react'
import { fireevent, render, screen } from '@testing-library/react'
import { useswrconfig } from 'swr'
import testcomponent from '@/components/test-component'

jest.mock('swr') // automock `swr` lib

test('mutate is called', () => {
    const mutatemock = jest.fn()
    useswrconfig.mockimplementationonce(() => ({ mutate: mutatemock })) // make sure you mock `mutate` and not `mutation`
    // using react-testing-library, but any other testing lib could be used
    render(<testcomponent />)
    fireevent.click(screen.getbyrole('button', { name: 'mutate' }))
    expect(mutatemock).tohavebeencalledwith('/api/user')
})

Related Query

More Query from same tag