【问题标题】:How to mock useSWRConfig implementation?如何模拟 useSWRConfig 实现?
【发布时间】:2022-01-22 23:47:20
【问题描述】:
有没有办法在 Jest 测试中模拟来自 SWR 的 useSWRConfig 钩子的实现?
import useSWR, { useSWRConfig } from 'swr';
it('should mutate', () => {
const mutation = jest.fn();
useSWR.mockImplementationOnce(() => ({ error: true })); // this works
useSWRConfig.mockImplementationOnce(() => ({ mutation })); // TypeError: _swr.useSWRConfig.mockImplementationOnce is not a function
expect(mutation).toHaveBeenCalled(); // not working
});
文档:https://swr.vercel.app/docs/mutation
【问题讨论】:
标签:
reactjs
jestjs
mocking
swr
【解决方案1】:
您可以自动模拟swr 模块,以便可以在useSWRConfig 上调用类似mockImplementationOnce 的模拟函数。
假设你有以下 React 组件。
import React from 'react'
import { useSWRConfig } from 'swr'
export default function TestComponent() {
const { mutate } = useSWRConfig()
return (
<button onClick={() => { mutate('/api/user') }}>
Mutate
</button>
)
}
您将在测试中模拟useSWRConfig 及其mutate 函数,如下所示。
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')
})