File size: 1,856 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
import React from 'react'
import { createEditor, Transforms } from 'slate'
import { act, renderHook } from '@testing-library/react'
import { Slate, withReact, Editable, useSlateSelector } from '../src'
import _ from 'lodash'
describe('useSlateSelector', () => {
test('should use equality function when selector changes', async () => {
const editor = withReact(createEditor())
const initialValue = [{ type: 'block', children: [{ text: 'test' }] }]
const callback1 = jest.fn(() => [])
const callback2 = jest.fn(() => [])
const { result, rerender } = renderHook(
({ callback }) => useSlateSelector(callback, _.isEqual),
{
initialProps: {
callback: callback1,
},
wrapper: ({ children }) => (
<Slate editor={editor} initialValue={initialValue}>
<Editable />
{children}
</Slate>
),
}
)
// One call in the render body, and one call in the effect
expect(callback1).toBeCalledTimes(2)
const firstResult = result.current
await act(async () => {
Transforms.insertText(editor, '!', { at: { path: [0, 0], offset: 4 } })
})
// The new call is from the effect
expect(callback1).toBeCalledTimes(3)
// Return values should have referential equality because of the custom equality function
expect(firstResult).toBe(result.current)
// Callback 2 has not been used yet
expect(callback2).toBeCalledTimes(0)
// Re-render with new function identity
rerender({ callback: callback2 })
// Callback 1 is not called
expect(callback1).toBeCalledTimes(3)
// Callback 2 is used instead
expect(callback2).toBeCalledTimes(1)
// Return values should have referential equality because of the custom equality function
expect(firstResult).toBe(result.current)
})
})
|