这个问题非常好:Jest每个测试用例如何mock模块
但它并没有回答我如何仅在一个单独的测试用例中mock它并保持其余测试使用原始组件。
如果我只想对快照进行一些 mocking,而其他测试不需要 mocking,那么这就有意义了。
这是我目前的尝试:
import React from 'react'
import { render } from '@testing-library/react'
jest.mock('components/Photo', () =>
jest.fn(() => jest.requireActual('components/Photo'))
)
import Photo from 'components/Photo'
import PhotoGrid from '.'
beforeEach(() => {
Photo.mockReset()
})
test('default renders 9 photos if provided 9', () => {
const photos = [...Array(9).keys()]
const { getAllByTestId, debug } = render(<PhotoGrid photos={photos} />)
debug()
expect(getAllByTestId(PHOTO_COMP_TEST_ID)).toHaveLength(9)
})
test('renders with masonry grid style', () => {
Photo.mockImplementation(() => <div />)
const photos = [...Array(9).keys()]
const { container, debug } = render(<PhotoGrid photos={photos} />)
debug()
expect(container).toMatchInlineSnapshot(`
<div>
...
</div>
`)
})
这是需要测试的组件
import React from 'react'
import Masonry from 'react-masonry-css'
import './index.css'
import Photo from 'components/Photo'
function PhotoGrid({ photos, numberOfPhotos = 9 }) {
const imgs = photos ? photos.slice(0, numberOfPhotos) : []
const breakpointColumnsObj = {
default: 4,
1300: 3,
900: 2,
700: 1,
}
return (
<Masonry
breakpointCols={breakpointColumnsObj}
className="my-masonry-grid"
columnClassName="my-masonry-grid_column"
>
{imgs &&
imgs.map(({ id, secret, server, farm }, index) => (
<div key={index} className="masonry-item">
<Photo id={id} secret={secret} server={server} farm={farm} />
</div>
))}
</Masonry>
)
}
export default PhotoGrid